【数据结构英文课件】LISTS AND STRINGS_第1页
【数据结构英文课件】LISTS AND STRINGS_第2页
【数据结构英文课件】LISTS AND STRINGS_第3页
【数据结构英文课件】LISTS AND STRINGS_第4页
【数据结构英文课件】LISTS AND STRINGS_第5页
已阅读5页,还剩99页未读 继续免费阅读

下载本文档

版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领

文档简介

1、Chapter 6 LISTS AND STRINGS,1. List Specifications,2. List Implementations,(a). Class Templates,(b). Contiguous,(c). Simply Linked,(d). Simply Linked with Position Pointer,(e). Doubly Linked,Chapter 6 LISTS AND STRINGS,3. Strings,4. Application: Text Editor,5. Linked Lists in Arrays,6. Application:

2、Generating Permutations,7. Pointers and Pitfalls,DEFINITION A list of elements of type T is a finite sequence of elements of T together with the following operations: 1. Construct the list, leaving it empty. 2. Determine whether the list is empty or not. 3. Determine whether the list is full or not.

3、 4. Find the size of the list. 5. Clear the list to make it empty. 6. Insert an entry at a specified position of the list. 7. Remove an entry from a specified position in the list. 8. Retrieve the entry from a specified position in the list. 9. Replace the entry at a specified position in the list.

4、10. Traverse the list, performing a given operation on each entry.,6.1 List Definition,Comparison with Standard Template Library:,The STL list provides only those operations that can be implemented efficiently in a List implementation known as doubly linked, which we shall study shortly. The STL lis

5、t does not allow random access to an arbitrary list position. The STL vector, does provide some random access to a sequence of data values, but not all the other capabilities we shall develop for a List. In this way, our study of the List ADT provides an introduction to both the STL classes list and

6、 vector.,List : List( ); Post: The List has been created and is initialized to be empty.,Method Specifications,void List : clear(); Post: All List entries have been removed; the List is empty.,bool List : empty() const; Post: The function returns true or false according to whether the List is empty

7、or not.,bool List : full() const; Post: The function returns true or false according to whether the List is full or not.,int List : size() const; Post: The function returns the number of entries in the List.,Position Number in a List,To find an entry in a list, we use an integer that gives its posit

8、ion within the list. We shall number the positions in a list so that the first entry in the list has position 0, the second position 1, and so on. Locating an entry of a list by its position is superficially like indexing an array, but there are important differences. If we insert an entry at a part

9、icular position, then the position numbers of all later entries increase by 1. If we remove an entry, then the positions of all following entries decrease by 1.,The position number for a list is defined without regard to the implementation. For a contiguous list, implemented in an array, the positio

10、n will indeed be the index of the entry within the array. But we will also use the position to find an entry within linked implementations of a list, where no indices or arrays are used at all.,Error_code List:insert(int position, const List_entry Post: If the List is not full and 0 position n, wher

11、e n is the number of entries in the List, the function succeeds:Any entry formerly at position and all later entries have their position numbers increased by 1, and x is inserted at position in the List. Else: The function fails with a diagnostic error code.,Error_code List : remove ( int position,

12、List_entry Post: If 0 positionn, where n is the number of entries in the List, the function succeeds: The entry at position is removed from the List, and all later entries have their position numbers decreased by 1. The parameter x records a copy of the entry formerly at position. Else: The function

13、 fails with a diagnostic error code.,Error_code List : retrieve(int position, List_entry all List entries remain unchanged. Else: The function fails with a diagnostic error code.,Error_code List : replace(int position, const List_entry all other entries remain unchanged. Else: The function fails wit

14、h a diagnostic error code.,void List:traverse(void (*visit)(List entry Post: The action specified by function *visit has been performed on every entry of the List, beginning at position 0 and doing each in turn.,6.2 Implementations of Lists,Class Templates,A C+ template construction allows us to wri

15、te code, usually code to implement a class, that uses objects of an arbitrary, generic type. In template code we utilize a parameter enclosed in angle brackets to denote the generic type. Later, when a client uses our code, the client can substitute an actual type for the template parameter. The cli

16、ent can thus obtain several actual pieces of code from our template, using different actual types in place of the template parameter.,Example: We shall implement a template class List that depends on one generic type parameter. A client can then use our template to declare several lists with differe

17、nt types of entries with declarations of the following form: List rst list; List second list;,Templates provide a new mechanism for creating generic data structures, one that allows many different specializations of a given data structure template in a single application. The added generality that w

18、e get by using templates comes at the price of slightly more complicated class specifications and implementations.,Contiguous(storage) Implementation,连续/顺序(存储)的,One-dimensional arrays,template class List public: / methods of the List ADT List( ); int size( ) const; bool full( ) const; bool empty( )

19、const; void clear( ); void traverse(void (*visit)(List_entry ,求顺序表的长度,判顺序表是否已满,判顺序表是否为“空,清空顺序表,遍历顺序表,查找表中第position 个元素存入x,将表中第position 个元素值修改为x,删除表中第position 个元素,其值存入x,将x插入表中 令其成为第 position个元素,protected: / data members for a contiguous list implementation int count; List_entry entrymax_list; ;,templ

20、ate int List:size( ) const / Post: The function returns the number of entries in the List . return count; ,template Error_code List :insert(int position, const List_entry ,template void List:traverse(void (*visit)(List_entry ,Performance of Methods,In processing a contiguous list with n entries: ins

21、ert and remove operate in time approximately proportional to n. List, clear, empty, full, size, replace, and retrieve operate in constant time.,Please follow the Error_code insert(int position, const List_entry ,Application: Contiguous List,设顺序表la和lb分别表示整数集合A和B,求:A=AB。,算法思路:集合中的元素是无重复的,可将Lb表中的元素从表尾起

22、逐个删除,并在La表查找被删元素b,若找不到,则将元素b插入La表,否则不必插入,完成后集合B为空。,在 List类中增加一个成员函数(方法):Find,template int List:Find(const List_entry ,下面给出:产生若干互不相等的随机整数(集合元素)插入表的函数:CrtSetList ;进行集合“并”运算的函数:SetUnion及主函数main()的源代码。,在class List_entry中 应当有定义,#include #include #include SQList.h void CrtSetList(List / 输入集合A,B元素数=15,以保证并

23、后La的元素数=30,coutnSet A = ; / 输出集合A的名称 CrtSetList(La,s1); / 创建集合A并输出集合元素 coutnSet B = ; / 输出集合B的名称 CrtSetList(Lb,s2); SetUnion(La,Lb); / 求集合A与集合B的并 coutnn A Union B = ; La.traverse(visit); cout n; ,void CrtSetList(List / 输出x ( 集合元素边产生边输出) ,void SetUnion(List ,Simply Linked Implementation,template stru

24、ct Node / Node declaration: Node_entry entry; Node *next; Node( ); / constructors Node(Node_entry, Node *link=NULL); / constructors ;,template class List / List declaration: public: / Specifications for the methods of the list ADT go here. / The following methods replace compiler-generated defaults.

25、,List( ); List(const List ,Actions on a Linked List,Finding a List Position,Function set position takes an integer parameter position and returns a pointer to the corresponding node of the list. Declare the visibility of set position as protected, since set position returns a pointer to, and therefo

26、re gives access to, a Node in the List. To maintain an encapsulated data structure, we must restrict the visibility of set position. Protected visibility ensures that it is only available as a tool for constructing other methods of the List. To construct set position, we start at the beginning of th

27、e List and traverse it until we reach the desired node:,template Node *List:set_position(int position) const /* Pre: position is a valid position in the List ;0 position *q = head; for (int i=0; inext; return q; ,If all nodes are equally likely, then, on average, the set position function must move

28、halfway through the List to find a given position. Hence, on average, its time requirement is approximately proportional to n, the size of the List.,template Error_code List : insert(int position, const List_entry ,Insertion Method,new_node = new Node(x, following); if(new_node=NULL)return overflow;

29、 if (position=0) head = new_node; else previous-next = new_node; count+; return success; ,Insert to Firsr entry,为了避免插入位置不同带来的处理方法的不一致,可以在第一个元素(“首元结点”)前,虚设一个结点称之为“头结点”;这样“头指针”指向“头结点”,如下图所示:,In processing a linked List with n entries: clear, insert, remove, retrieve, and replace require time approxima

30、tely proportional to n. List, empty, full, and size operate in constant time.,Variation: Keeping the Current Position,Suppose an application processes list entries in order or refers to the same entry several times before processing another entry. Remember the last-used position in the list and, if

31、the next operation refers to the same or a later position, start tracing through the list from this last-used position.,Note that this will not speed up every application using lists. The method retrieve is defined as const, but its implementation will need to alter the last-used position of a List.

32、 To enable this, we use the mutable qualifier. Mutable data members of a class can be changed, even by constant methods.,template class List public: / Add specifications for the methods of the list ADT. / Add methods to replace the compiler-generated defaults. protected: / Data members for the linke

33、d-list implementation with / current position follow:,All the new class members have protected visibility, so, from the perspective of a client, the class looks exactly like the earlier implementation. The current position is now a member of the class List, so there is no longer a need for set posit

34、ion to return a pointer; instead,the function simply resets the pointer current directly within the List.,int count; mutable int current position; Node *head; mutable Node *current; / Auxiliary function to locate list positions follows: void set_position(int position) const; ;,template void List : s

35、et_position(int position) const /* Pre: position is a valid position in the List : 0next; ,For repeated references to the same position, neither the body of the if statement nor the body of the for statement will be executed, and hence the function will take almost no time.,If we move forward only o

36、ne position, the body of the for statement will be executed only once, so again the function will be very fast. If it is necessary to move backwards through the List, then the function operates in almost the same way as the version of set position used in the previous implementation.,下面将Simply (sing

37、le) Linked类的声明部分给出,实现及测试演示给大家(源代码可以复制给大家) 。,#include enum Error_code success, fail, range_error ; template struct Node / Node declaration Node_entry entry; Node *next; Node( ) next=NULL; Node(Node_entry data, Node *link=NULL) entry=data; next=link; ; template class List / Single lined list declarati

38、on public: List() count=0; head = NULL; / constructor List(const List / destructor,List,注 Simply (single) Linked类的文件名如下: 声明及实现:SLList.h 测试程序: exp_slink.cpp,Doubly Linked Lists,protected: Node *head; /pointer: point to first node int count; /number of List_entry Node *set_position(int position) const

39、; ;,Node definition:,template struct Node / data members Node_entry entry; Node *next; Node *back; / constructors Node( ); Node(Node_entry, Node *link_back = NULL, Node *link_next = NULL); ;,List definition:,template class List public: / Add specifications for methods of the list ADT. / Add methods

40、to replace compiler generated defaults. protected: / Data members for the doubly-linked list implementation follow: int count; mutable int current_position; mutable Node *current; / The auxiliary function to locate list positions follows: void set_position(int position) const; ;,We can move either d

41、irection through the List while keeping only one pointer, current, into the List. We do not need pointers to the head or the tail of the List, since they can be found by tracing back or forth from any given node. To find any position in the doubly linked list, we rst decide whether to move forward o

42、r backward from the current position,and then we do a partial traversal of the list until we reach the desired position.,template void List : set_position(int position) const /* Pre: position is a valid position in the List : 0 position next; else for ( ; current_position != position; current_positi

43、on-) current = current-back; ,The cost of a doubly linked list is the extra space required in each Node for a second link, usually trivial in comparison to the space for the information member entry.,Insertion into a Doubly Linked List,template Error code List : insert(int position, const List entry

44、 ,if (position = = 0) if (count = = 0) following = NULL; else set_position(0); following = current; preceding = NULL; else set_position(position - 1); preceding = current; following = preceding-next; new_node = new Node(x, preceding, following); if (new node = = NULL) return overflow; if (preceding

45、!= NULL) preceding-next = new_node; if (following != NULL) following-back = new_node; current = new_node; current_position = position; count+; return success; ,下面将Doubly Linked List类的声明部分给出, 实现及测试演示给大家(源代码可以复制给大家) 。,注 文件名如下: 声明及实现:DLList.h 测试程序: exp_dlink.cpp,# include enum Error_code success, fail,

46、 range_error ; template / Node declaration struct Node / data members Node_entry entry; Node *next; Node *back; / constructors Node(); Node( Node_entry, Node *link_back = NULL, Node *link_next = NULL); ;,声明双向链表的结点结构,结点的数据域 其类型为模板 Node_entry,指向下一结点的指针,指向前一结点的指针,将next和back 置为“空”的 constructor1,next和bac

47、k缺省值 为“空”(数据域及 指针均被初始化) 的constructor2,template Node:Node() next = back = NULL; template Node: Node ( List_entry data, Node *link_back,Node *link_next ) entry = data; back = link_back; next = link_next; ,以双向链表的数据项 做为结点的数据域,Implementation constructor1,Implementation constructor2,template class List /

48、doubly lined list declaration public: List(); / constructor List(const List ,Error_code retrieve(int position, List_entry ,小结,顺序表的特点是:逻辑上相邻的元素,存储位置也相邻。由此可知,线性表采用顺序存储有如下的优缺点: 其优点是: 不需为表示元素间的逻辑关系而增加额外存储空间; 可以方便地随机存取表中的任一结点。 其缺点是: 插入和删除运算不方便,除表尾位置外,在表的其它位置上进行插入和删除操作都必须移动大量元素,因此效率较低; 由于顺序表要求占用连续的存储单元,必须

49、预留存储空间,因此当表长变化较大时,难以确定合适的存储规模,若按可能达到的最大长度留表空间,则可能造成一部分空间长期闲置而得不到充分利用,若事先对表长估计不足,则插入操作可能使表长超过预先分配的空间而造成溢出。,线性表的链式存储正是针对顺序存储的缺点而提出的。,Comparison of Implementations,Contiguous storage is generally preferable when the entries are individually very small; when the size of the list is known when the progra

50、m is written; when few insertions or deletions need to be made except at the end of the list; and when random access is important. Linked storage proves superior when the entries are large; when the size of the list is not known in advance; and when flexibility is needed in inserting, deleting, and

51、rearranging the entries.,To choose among linked list implementations, consider:,Which of the operations will actually be performed on the list and which of these are the most important? Is there locality of reference? That is, if one entry is accessed, is it likely that it will next be accessed agai

52、n? Are the entries processed in sequential order? If so, then it may be worthwhile to maintain the last-used position as part of the list structure. Is it necessary to move both directions through the list? If so,then doubly linked lists may prove advantageous.,6.3 STRINGS,Strings in C,A string is d

53、efined as a sequence of characters. Examples: This is a string or Name?, where the double quotes are not part of the string. The empty string is . A string ADT is a kind of list, but the operations are usually quite different from other lists. The first implementation of strings is found in the C su

54、bset of C+. We call these C-strings. C-strings reflect the strengths and weaknesses of the C language:, C-strings are widely available. C-strings are very efficient. C-strings objects are not encapsulated. C-strings are easy to misuse, with consequences that can be disastrous. It is easy for a clien

55、t to create either garbage or aliases for C-string data. For example:,Every C-string has type char *. Hence, a C-string references an address in memory, the rst of a contiguous set of bytes that store the characters making up the string. The storage occupied by the string must terminate with the spe

56、cial character value 0. The standard header le (or ) contains a library of functions that manipulate C-strings. In C+, the output operator is overloaded to apply to Cstrings, so that a simple instruction cout s prints the string s. In C+, it is easy to use encapsulation to embed C-strings into safer

57、 class-based implementations of strings.,The standard template library includes a safe string implementation in the header le . This library implements a class called std : string that is convenient, safe, and efficient.,Standard C-String Library,char *strcpy(char *to, char *from); Pre: The string f

58、rom has been initialized. Post: The function copies string from to string to, including 0; it returns a pointer to the beginning of the string to.,char *strncpy(char *to, char *from, size_t n); Pre: The string from has been initialized. Post: The function copies at most n characters from string from to string to; it returns a pointer to the string to. If from has less than n characters, the remaining positions are padded with 0s.,char *strcat(char *to, char *from); Pre: The strings from and to have been initialized. Post: The function copies string from to

温馨提示

  • 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
  • 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
  • 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
  • 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
  • 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
  • 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
  • 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。

评论

0/150

提交评论