Presentation is loading. Please wait.

Presentation is loading. Please wait.

Lists Briana B. Morrison Adapted from Alan Eugenio & William J. Collins.

Similar presentations


Presentation on theme: "Lists Briana B. Morrison Adapted from Alan Eugenio & William J. Collins."— Presentation transcript:

1 Lists Briana B. Morrison Adapted from Alan Eugenio & William J. Collins

2 Lists 2 Topics Review from Lists Implementing a linked list Doubly linked Dummy header node In an array Function Implementation Dynamic memory management

3 Lists 3 Abstract Model of a List Object

4 Lists 4

5 5 Model of a list object with links to next and previous element

6 Lists 6

7 7 The List ADT The list API documents the member function prototype as well as pre- and postconditions.

8 Lists 8 CLASS list Constructors list(); Create an empty list. This is the default constructor. list(int n, const T&value = T()); Create a list with n elements, each having a specified value. If the value argument is omitted, the elements are filled with the default value for type T. Type T must have a default constructor, and the default value of type T is specified by the notation T(). list(T *first, T *last); Initialize the list, using the address range [first, last).

9 Lists 9 The List Constructors provides three constructors to declare a list object.

10 Lists 10 CLASS list Operations T& back(); Return the value of the item at the rear of the list. Precondition: The list must contain at least one element. bool empty() const; Return true if the list is empty, false otherwise. T& front(); Return the value of the item at the front of the list. Precondition: The list must contain at least one element.

11 Lists 11 Using Front, Back and Empty int arr[5] = {9, 2, 7, 3, 12}; list lst(arr,arr+5); cout << lst.back( ); lst.back( ) = 99; cout << lst.front( ); lst.front( ) = 46; If (lst.empty( )) cout << Empty);

12 Lists 12 CLASS list Operations void push_back(const T& value); Add a value at the rear of the list. Postcondition: The list has a new element at the rear, and its size increases by 1. void pop_back(); Remove the item at the rear of the list. Precondition:The list is not empty. Postcondition:The list has a new element at the rear or is empty.

13 Lists 13 CLASS list Operations void push_front(const T& value); Add a value at the front of the list. Postcondition:The list has a new element at the front, and its size increases by 1. void pop_front(); Remove the item at the front of the list. Precondition:The list is not empty. Postcondition:The list has a new element at the front or is empty. int size() const; Return the number of elements in the list.

14 Lists 14 Using Push, Pop, and Size int arr[5] = {9, 2, 7, 3, 12}; list lst(arr,arr+5); lst.pop_back( ); lst.push_back(99); lst.pop_front( ); lst.push_front(11); cout << lst.size( );

15 Lists 15

16 Lists 16

17 Lists 17 CLASS list Operations iterator begin(); Returns an iterator that references the first position (front) of the list. If the list is empty, the iterator value end() is returned. const_iterator begin(); Returns a const_iterator that points to the first position (front) of a constant list. If the list is empty, the const_iterator value end() is returned.

18 Lists 18 CLASS list Operations iterator end(); Returns an iterator that signifies a location immediately out of the range of actual elements. A program must not dereference the value of end() with the * operator. const_iterator end(); Returns a const_iterator that signifies a location immediately out of the range of actual elements in a constant list. A program must not dereference the value of end() with the * operator.

19 Lists 19 Using Iterators To declare an iterator: list ::iterator listIter; list ::iterator iter; Using an iterator: list intList; listIter = intList.begin();//initialize listIter = intList.end();//past end of list

20 Lists 20 CLASS list Operations void erase(iterator pos); Erase the element pointed to by pos. Precondition:The list is not empty. Postcondition:The list has one fewer element. void erase(iterator first, iterator last); Erase all list elements within the iterator range [first, last]. Precondition:The list is not empty. Postcondition:The size of the list decreases by the number of elements in the range.

21 Lists 21 CLASS list Operations iterator insert(iterator pos, const T& value); Insert value before pos, and return an iterator pointing to the position of the new value in the list. The operation does not affect any existing iterators. Postcondition:The list has a new element.

22 Lists 22 Using Insert and Erase int arr[5] = {9, 2, 7, 3, 12}; list lst(arr,arr+5); list ::iterator listIter; listIter = lst.end( ); lst.insert(listIter, 14); listIter = lst.begin( ); listIter = lst.insert(listIter, 55); lst.erase(listIter);

23 Lists 23 CLASS list::iterator Operations * :Accesses the value of the item currently pointed to by the iterator.*iter; ++ :Moves the iterator to the next item in the list.iter++; -- :Moves the iterator to the previous item in the list.iter--; == :Takes two iterators as operands and returns true when they both point at the same item in the list. iter1 == iter2 != :Returns true when the two iterators do not point at the same item in the list. iter1 != iter2

24 Lists 24 Using Insert and Erase int arr[5] = {9, 2, 7, 3, 12}; list lst(arr,arr+5); list ::iterator listIter; listIter = lst.begin( ); listIter++; cout << *listIter; lst.insert(listIter, 44); listIter--; lst.erase(listIter);

25 Lists 25 Note about Iterators List iterators move through the list in a circular fashion. When an iterator is at end(), the operation++ move the iterator to the first list element, at location begin(); Similarly, when an iterator is at begin(), the operation -- moves the iterator to end();

26 Lists 26 iterator versus const_iterator Each standard library container (e.g. the list) provides both an iterator and a const_iterator The operations on them are the same, except When a const_iterator is dereferenced ( operator* ), the value of the item referenced cannot be changed.

27 Lists 27 Constant Iterators STL has a second type of iterator, constant iterator. Much like regular iterator except you cannot apply dereference (*) to a constant iterator on the left side of an assignment statement. Cannot be used with list insert() and erase() Can use ++ and -- to move through list. Rule: use constant iterator to access and scan a constant list. list ::const_iterator iter;

28 Lists 28 Iterator Hierarchy

29 Lists 29 Iterator Functions

30 Lists 30

31 Lists 31

32 Lists 32 Inserting an element into a list list intList (arr, arr+arrSize); list ::iterator iter, newElt; iter = intList.begin(); iter++; newElt = intlist.insert ( iter, 4);

33 Lists 33 Removing an element from a list list intList (arr, arr+arrSize); list ::iterator iter; iter = intList.begin(); iter++; intlist.erase (iter);

34 Lists 34 Ordered lists Position the iterator curr at the front of the list. Insert 50 in the list: curr = intList.begin(); intList.insert (curr, 50);

35 Lists 35 insertOrder() //insert item into the ordered list template <typename T. void insertOrder (list & orderedList, const T& item) { // curr starts at first list element, stop marks end list ::iterator curr = orderedList.begin(), stop = orderList.end(); // find the insertion point while ((curr != stop) && (*curr < item)) curr++; // do the insertion using insert() orderedList.insert (curr, item); }

36 Lists 36

37 Lists 37

38 Lists 38 Users Guide for choosing a list or vector If the application entails a lot of accessing and/or modifying items at widely varying positions, a vector will be much faster than a list. If a large part of the application consists of iterating through a container and making insertions and/or deletions during the iterations, a list will be much faster than a vector.

39 Lists 39

40 Lists 40

41 Lists 41

42 Lists 42 Splicing two lists 715163471534734 destList 1516 sourceIter sourceList pos 5 destList (After insert of 15) 1516 sourceIter sourceList pos 5 destList (After insert of 16) sourceList pos 5 destList.splice(pos, sourceList);

43 Lists 43

44 Lists 44

45 Lists 45

46 Lists 46 apple banana candy donut egg

47 Lists 47 Linked List Basics Node Composition Inserting at Front Deleting at Front Inserting in Middle Deleting from Middle

48 Lists 48 Node Composition An individual Node is composed of two parts, a Data field containing the data stored by the node, and a Pointer field that marks the address of the next Node in the list.

49 Lists 49 A List Node A node contains: A data item One or more links A link is a pointer to a list node The node class is usually defined inside another class: It is a hidden inner class The details of a node should be kept private

50 Lists 50 List Nodes for Singly-Linked Lists

51 Lists 51 Inserting at the Front of a Linked List

52 Lists 52 Deleting From the Front of a Linked List

53 Lists 53 Removing a Target Node

54 Lists 54 Doubly Linked Lists Structure Inserting Circular doubly linked

55 Lists 55 Doubly-Linked Lists Limitations of a singly-linked list include: Can insert only after a referenced node Removing node requires pointer to previous node Can traverse list only in the forward direction We can remove these limitations: Add a pointer in each node to the previous node: doubly-linked list

56 Lists 56 Designing a New Linked List Structure

57 Lists 57 Doubly-Linked Lists, The Diagrams

58 Lists 58 Inserting a Node at a Position

59 Lists 59 Deleting a Node at a Position

60 Lists 60 Circular Doubly Linked Lists A Watch Band provides a good Real Life analogue for this Data Structure

61 Lists 61 Circular Lists Circular doubly-linked list: Link last node to the first node, and Link first node to the last Advantages: Can easily keep going past ends Can visit all elements from any starting point Can never fall off the end of a list Disadvantage: code must avoid infinite loop! Can also build singly-linked circular lists: Traverse in forward direction only

62 Lists 62 Circular Doubly Linked Lists Implemented on a Computer it might look something like this.

63 Lists 63 Implementing a Circular List

64 Lists 64 Updating a Doubly Linked List

65 Lists 65 struct versus class A struct is the same as a class. Except that the default visibility for a struct is public. Generally struct s are used to define classes that only contain public data fields. Constructors may be provided. Other member functions (operators) are usually not defined for struct s.

66 66 // Type DECLARATIONS struct NodeType { char info; NodeType* prev; NodeType* next; } typedef NodeType* NodePtr; // Variable DECLARATIONS NodePtr head; NodePtr ptr; Declarations for a Dynamic Linked List. prev. info. next 5000 A 6000

67 67 Pointer Dereferencing and Member Selection. info. next A 6000 ptr. info. next A 6000 *ptr ptr. info. next (*ptr).info ptr->info A 6000

68 68 ptr is a Pointer to a Node. info. next A 6000 ptr

69 69 *ptr is the Entire Node Pointed to by ptr ptr. info. next A 6000 *ptr

70 70 ptr->info Is a Node Member ptr. info. next ptr->info (*ptr).info // equivalent A 6000

71 71 ptr->link Is a Node Member ptr. info. next ptr->next (*ptr).next // equivalent A 6000

72 Lists 72 Inserting a Node into a Single Linked List Node* bob = new Node("Bob"); bob->next = harry->next; // step 1 harry->next = bob; // step 2

73 Lists 73 Removing a node from a single-linked list Node* ptr = tom->next; tom->next = tom->next->next; delete ptr;

74 Lists 74 Inserting into a Double-Linked List DNode* sharon = new DNode("Sharon"); // Link new DNode to its neighbors sharon->next = sam; // Step 1 sharon->prev = sam->prev; // Step 2

75 Lists 75 Inserting into a Double-Linked List (2) // Link old predicessor of sam to new predicessor. sam->prev->next = sharon; // Step 3 // Link to new predicessor. sam->prev = sharon; // Step 4

76 Lists 76 Removal from a Double-Linked List harry->prev->next = harry->next; // Step 1 harry->next->prev = harry->prev; // Step 2 delete harry;

77 Lists 77

78 Lists 78

79 Lists 79

80 Lists 80

81 Lists 81

82 Lists 82 /** Construct an empty list. */ list() { node = new list_node(); node->next = node; node->prev = node; length = 0; }

83 Lists 83

84 Lists 84

85 Lists 85

86 Lists 86

87 Lists 87

88 Lists 88

89 Lists 89

90 Lists 90

91 Lists 91

92 Lists 92 Linked Lists in Arrays Begin with a large workspace array and regard the array as our allocation of unused space. Set up functions to keep track of which parts of the array are unused and to link entries of the array together in the desired order. The one feature of linked lists that you invariably lose in this implementation method is the dynamic allocation of storage.

93 Lists 93 Linked Lists in Arrays Applications where linked lists in arrays may prove preferable are those where: The number of entries in a list is known in advance, The links are frequently rearranged, but relatively few additions or deletions are made, or The same data are sometimes best treated as a linked list and other times as a contiguous list.

94 Lists 94 Example

95 Lists 95

96 Lists 96 Implementations What are the data members? What is the logic for insert and delete? How would you keep track of the iterator?

97 Lists 97 Set Position How would you implement the following: Singly linked Doubly linked Array based implementation 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

98 Lists 98 Insert Function template void List ::insert ( int position, const List_entry &x);

99 Lists 99 Summary Slide 1 §- list -A Sequence of elements stored by position. -Index access is not available… §-to access the value of an element, must pass through its preceding elements. §- list iterator -A generalized pointer that moves through a list element by element… forward or backward -At any point, the * operator accesses the value of a list item.

100 Lists 100 100 Summary Slide 2 §- The list class has two iterator types: 1)iterator 1)iterator: A generalized list traversal pointer. 2)const_iterator 2)const _ iterator: :: must be used with a constant list object. Each type is a nested class of list and must be accessed by using the scope operator ::

101 Lists 101 101 Summary Slide 3 §- the list member function begin() -Gives an iterator an initial value that points to the first element. §- the list member function end() -Returns an iterator pointing just past the last element of the list.

102 Lists 102 102 Summary Slide 4 §- The sequential search of a list object firstlast -implemented by using an iterator range [first, last). last -It returns an iterator that points at the target value or has value last if the target is not in the list.

103 Lists 103 103 Summary Slide 5 §- list class member f ns insert() and erase() -Both use an iterator argument to modify a list. 1)insert() pos 1)insert(): places value in the list before the data referenced by the iterator pos. 2)erase() pos 2)erase(): removes the data item referenced by pos from the list.

104 Lists 104 104 Summary Slide 6 §- singly linked lists -Each node contains a value and a pointer to the next node in the list. -The list begins with a pointer to the first node of the list and terminates when a node has a NULL pointer.

105 Lists 105 105 Summary Slide 7 §- Inserting/Deleting at the front of a singly linked list 1)Insert -Set the pointer in the new node to the previous value of front. -update front to point at the new node. 2)Erase -assign front the pointer value of the first node, and then delete the node.

106 Lists 106 106 Summary Slide 8 §- Inserting/Erasing inside a singly linked list -Maintain a pointer to the current list node and a pointer to the previous node. -Change the pointer value in the previous node.

107 Lists 107 107 Summary Slide 9 §- Insert/Delete at the back of a singly linked list -Maintain a pointer to the last list node that has value NULL when the list is empty. -Assign a back pointer the address of the first node added to the list. -To add other nodes at the back: 1)allocate a new node 2)assign the pointer in node back to point to the new node 3)assign the pointer back the address of the new node.

108 Lists 108 108 Summary Slide 10 §- Doubly linked lists -provide the most flexible implementation for the sequential list. §- Its nodes have pointers to the next and the previous node, so the program can traverse a list in either the forward or backward direction. -Traverse a list by starting at the first node and follow the sequence of next nodes until you arrive back at the header. -To traverse a list in reverse order, start at the last node and follow the sequence of previous nodes until arriving back at the header.


Download ppt "Lists Briana B. Morrison Adapted from Alan Eugenio & William J. Collins."

Similar presentations


Ads by Google