Presentation is loading. Please wait.

Presentation is loading. Please wait.

Chapter 6 LISTS AND STRINGS 1. List Definition 2. List Implementations (a) Class Templates (b) Contiguous (c) Simply Linked (d) Doubly Linked 3. Linked.

Similar presentations


Presentation on theme: "Chapter 6 LISTS AND STRINGS 1. List Definition 2. List Implementations (a) Class Templates (b) Contiguous (c) Simply Linked (d) Doubly Linked 3. Linked."— Presentation transcript:

1 Chapter 6 LISTS AND STRINGS 1. List Definition 2. List Implementations (a) Class Templates (b) Contiguous (c) Simply Linked (d) Doubly Linked 3. Linked Lists in Arrays 4. Strings 5. Application: Generating Permutations

2 List Definition 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. 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. 10. Traverse the list, performing a given operation on each entry.

3 Position Number in a List To find an entry in a list, we use an integer that gives its position within the list. the first entry in the list has position 0, the second position 1, and so on. If we insert an entry at a particular 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.

4 Implementation of Lists Contiguous (Contiguous List) Linked (Linked List) –Simple Linked List –Doubly Linked List Describe List using template class for its generality –In template code we utilize a parameter to denote the generic type template //a generic entry type class List{ // Add in member information for the class };

5 Contiguous Lists Template class List { public: //methods of the List ADT list(); int size() const; bool full() const; bool empty() const; void clear() ; void traverse(void(*visit)(List_entry &)); // *visit - function Error_code retrieve(int position, List_entry &x) const; Error_code replace(int position, const List_entry &x) ; Error_code remove(int position, List_entry &x) ; Error_code insert(int position, const List_entry &x); ……

6 Contiguous Lists (continue) protected: //data members for a contiguous list implementation int count; List_entry entry[max_list]; };

7 template int List ::size() const { return count; } Implementation of Contiguous Lists template int List ::list() const { count = 0; }

8 template Error_code List::insert(int position, const List_entry&x) { if(full()) return overflow; if(position count) return range_error; for(int i=count-1;i>=position;i--) //move entry[i+1]=entry[i]; entry[position]=x; //insert count ++; return success; } Analysis: Implementation of Contiguous Lists

9 template 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. */ { for (int i = 0; i < count; i++) (*visit)(entry[i]); //*visit stands for a function name } Implementation of Contiguous Lists

10 Other Operations The remaining operations for contiguous lists will all be left as exercises. See page 231. Analysis In processing a contiguous list with n entries –Insert and remove require time approximately proportional to n, O(n). –List , clear , empty , full , size , replace and retrieve operate in constant time, O(1). Implementation of Contiguous Lists

11 template Error_code List :: retrieve(int position, List_entry &x) const { if(empty()) return underflow; if(position count) return range_error; x = entry[position]; return success; } Implementation of Contiguous Lists

12 Simple Linked List

13 Template struct Node { // data members Node_entry entry; Node *next; // constructors Node(); Node(Node_entry,Node *link=NULL); }; Node of Simple Linked List entry next

14 Template class List{ public: list(); int size() const; bool full() const; bool empty() const; void clear() ; void traverse(void(*visit)(List_entry &)); Error_code retrieve(int position, List_entry &x) const; Error_code replace(int position, const List_entry &x) ; Error_code remove(int position, List_entry &x) ; Error_code insert(int position, const List_entry &x); Class of Simple Linked List

15 ~List(); //destructor protected: int count; Node *head; Node *set_position(int position) const; //Returns a pointer to the Node in position }; Class of Simple Linked List

16 Examples insert the word ”simple” before the word “Lists” Initial sentence “Stacks are lists”

17 Examples replace “Lists” by “structures” and insert three nodes “but important data” remove “simple but”

18 Template Node *List ::set_position(int position) const /* Pre: position is a valid position in the List;0<=position<count. Post:Returns a pointer to the Node in position.*/ { Node *q=head; for(int i=0; i next; return q; } // Analysis: If all nodes are equally likely , then , on average , the set_position function must move 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 。 Implementation of Simple Linked List

19 template Error_code List ::insert(int position, const List_entry&x) { if (position count) return range_error; Node *new_node, *previous, *following; if (position > 0) { //decide the previous and following node previous = set_position(position -1); following = previous->next; } else following = head; new_node = new Node (x, following); //create new node if (new_node == NULL) return overflow; if (position == 0) head = new_node; //insert new node into list else previous->next = new_node; count++; return success; } Implementation of Simple Linked List

20

21 Other Operations –The remaining operations for linked lists will all be left as exercises 。 See page 232 。 Analysis In processing a linked List with n entries: –Clear,insert,remove,retrieve,and replace require time approximately proportional to n 。 –List,empty,full,and size in constant time 。 Implementation of Simple Linked List

22 Doubly Linked List Some applications of linked lists require that we frequently move both forward and backward through the list 。 It is more flexible. A doubly linked list

23 Template struct Node { // data members Node_entry entry; Node *next; Node *back; // constructors Node(); Node(Node_entry, Node *link_back=NULL, Node *link_back=NULL); }; Node of Doubly Linked List entrybacknext

24 Template class List { public: list(); int size() const; bool full() const; bool empty() const; void clear() ; Error_code retrieve(int position, List_entry &x) const; Error_code replace(int position, const List_entry &x) ; Error_code remove(int position, List_entry &x) ; Error_code insert(int position, const List_entry &x); ~List(); //destructor List(const List &copy); //copy constructor void operator=(const List &copy); protected: int count; int current_position; Node *current; void set_position(int position) const; //find the position node }; ADT of Doubly Linked 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.

25 Insertion

26 Analysis of Doubly Linked Lists The doubly linked list is more flexible for moving both forward and backward through the list 。 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.

27 Comparison of Contiguous and Linked Implementations of List Advantages of Linked List –The foremost advantage of linked lists in dynamic storage is flexibility 。 –Overflow is no problem until the computer memory is actually exhausted for linked list 。 –Changes , especially insertions and deletions , can be made in the middle of a linked list more quickly than in the middle of a contiguous list 。 Disadvantages of Linked List –The first drawback: Links themselves take space –The major drawback: Not suited to random access, or say, can not access entries directly.

28 Contiguous storage is generally preferable –When the entries are individually very small; –When the size of the list is known when the program 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 need in inserting , deleting , and rearranging the entries 。 Summary of Contiguous and Linked List

29 3. Linked List in Arrays

30 Note: Value –1 indicates the end of the list, two arrays for each linked list. Exercise: Page 258, E1 Example: A small part of student record system, ordered by name, math marks and CS marks.

31 4.Strings Definition Char –For example: ‘a’, ‘1’, ’\n’, ‘ ’ String –A string is a sequence of characters, it is a kind of list but with different operations. –For example: “this is a string”, “why”, “a” Usage of string –Text editor –Information retrieval –Compiler

32 Definition C-string –C implementation of strings, also available in C++. –Every string has type char * –The storage occupied by the string must terminate with the special character value ‘\0’ –The standard header file (or ) contains a library of functions that manipulate C-strings –In C++, the output operator << is overloaded to apply to cstrings, so that instruction cout << s prints the string s

33 Standard C-String Library char *strcpy(char *to, char *from); –copies string from to string to, including ‘\0’; char *strncpy(char *to, char *from, int n); –copies at most n characters from string from to string to; char *strcat(char *to, char *from); –copies string from to the end of string to, including ‘\0’; char *strncat(char *to, char *from, int n); –copies at most n characters from string from to the end of string to; int strlen(char *s); –returns the length of the string s, not including ‘\0’;

34 Standard C-String Library int strcmp(char *s1, char *s2); –compares string s1 to string s2; int strncmp(char *s1, char *s2, int n); –compares at most n characters of string s1 to string s2; char *strchr(char *s, char c); –returns a pointer to the first occurrence of the character c in the string s; char *strrchr(char *s, char c); –returns a pointer to the last occurrence of the character c in the string s; char *strstr(char *s1, char *s2); –returns a pointer to the first occurrence of the string s2 in the string s1;

35 Drawback of C-string It is easy for creating either memory garbage or aliases for string data. Many functions fail for presenting a NULL string object. Solutions: Safe Implementation of Strings Lost data Alias data s t s = t “ important string” “acquires an alias” char * x = NULL; cout << strlen(x);

36 Safe Implementation of Strings To create a safer string implementation, we embed the C- string representation as a member of a class String. Features: –Include the string length as a data member in the String class. –The String class avoids the problems of aliases, garbage creation, and uninitialized objects by including an overloaded assignment operator, a copy constructor, a destructor, and a constructor. –Include overloaded versions of the Boolean comparison operators, =, ==, !=. –Include a constructor that uses a parameter of type char * and translates from C-string objects to String objects. –Include a constructor to convert from a List of characters to a String. –Include a String method c_str( ) that converts String objects to corresponding C-string objects. –The resulting String class is a fully encapsulated ADT, but it provides a complete interface both to C-strings and to lists of characters.

37 ADT of String class String { public: // methods of the string ADT String( ); String (const char * copy); // conversion from C-string String (List &copy); // conversion from List String (const String &copy); // copy constructor const char *c_str( ) const; // conversion to C-string void operator = (const String &copy); protected: char *entries; int length; }; bool operator == (const String &rst, const String &second); bool operator > (const String &rst, const String &second); bool operator < (const String &rst, const String &second); bool operator >= (const String &rst, const String &second); bool operator <= (const String &rst, const String &second); bool operator != (const String &rst, const String &second);

38 Applications of String --Text Editor Operations See Page 242

39

40 Generating Permutations


Download ppt "Chapter 6 LISTS AND STRINGS 1. List Definition 2. List Implementations (a) Class Templates (b) Contiguous (c) Simply Linked (d) Doubly Linked 3. Linked."

Similar presentations


Ads by Google