Download presentation
Presentation is loading. Please wait.
Published byLester Jones Modified over 9 years ago
1
More Linking Up with Linked Lists Chapter 11 5/19/2015 Adopted from instructor resource slides Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights reserved. 0-13-140909-3 1
2
Lists (Review) Properties of a list: Homogeneous Finite length Sequential elements Basic Operations for a List Class: Constructor empty() insert() delete() display() Implementation involves Defining data members Defining function members from design phase Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights reserved. 0-13-140909-3 2
3
Using a Template? (Review) By writing ‘template’ before a class definition, the class can be used with any data type Allows for flexibility/versatility Template could use any data type represented by T T can be any of C++ defined data types (int, char, etc) or one that is user-defined Different ways to implement a template, can declare and implement in one.h file Better approach is to have template class definition in header file and implementation in it’s own.cpp file In this instance, will need to add the line: Template before each function header Each function name is preceded with classname :: Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights reserved. 0-13-140909-3 3
4
Array-Based Implementation of Lists (Review) An array is a viable choice for storing list elements Element are sequential It is a commonly available data type Algorithm development is easy Normally sequential orderings of list elements match with array elements 4
5
List Class with Static Array (Review) Use template template class List { public: List(); bool isEmpty() const; bool insert(const T&, const int&); bool remove(const int&); void display(ostream&) const; private: T _items[CAPACITY]; // array to store list elements int _size; // current size of the list stored in _items }; 5
6
List Class with Static Array – Problems (Review) Stuck with "one size fits all" Could be wasting space Could run out of space Better to have instantiation of specific list specify what the capacity should be Thus we consider creating a List class with dynamically- allocated array 6
7
Dynamic-Allocation for List Class Changes required in data members Eliminate const declaration for CAPACITY Add variable data member to store capacity specified by client program Change array data member to a pointer Constructor requires considerable change Little or no changes required for empty() display() erase() insert() 7
8
List Class with Dynamic Array template class List { public: List(); bool isEmpty() const; bool insert(const T&, const int&); bool remove(const int&); void display(ostream&) const; private: T* _items; // array to store list elements int _size; // current size of the list stored in _items int_capacity; //current amount of allocated memory }; 8
9
New Functions Needed (Review) “Rule of 3” if need one, probably need all 3 of these functions Destructor When class object goes out of scope the pointer to the dynamically allocated memory is reclaimed automatically The dynamically allocated memory is not The destructor reclaims dynamically allocated memory Copy Constructor When argument passed as value parameter When function returns a local object When temporary storage of object needed When object initialized by another in a declaration Assignment Operator Default assignment operator makes shallow copy Can cause memory leak, dynamically-allocated memory has nothing pointing to it Function would essentially create a new array and copy the element values of the existing array, into the new array Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights reserved. 0-13-140909-3 9
10
10 http://www.screeninsults.com/ghostbusters.php http://www.american-buddha.com/GHOST.253.htm
11
Linked List Linked list NODE contains Data part – stores an element of the list Next part – stores link/pointer to next element (when no next element, null value) 11
12
Linked Lists - Advantages Access any item as long as external link to first item maintained Insert new item without shifting Delete existing item without shifting Can expand/contract as necessary 12
13
Linked Lists - Disadvantages Overhead of links: used only internally, pure overhead If dynamic, must provide destructor copy constructor Assignment operator No longer have direct access to each element of the list Many sorting algorithms need direct access Binary search needs direct access Access of n th item now less efficient must go through first element, and then second, and then third, etc. 13
14
Linked Lists - Disadvantages List-processing algorithms that require fast access to each element cannot be done as efficiently with linked lists. Consider adding an element at the end of the list 14 ArrayLinked List a[size++] = value; Get a new node; set data part = value next part = null_value If list is empty Set first to point to new node. Else Traverse list to find last node Set next part of last node to point to new node. This is the inefficient part
15
Data Members for Linked-List Implementation A linked list will be characterized by**: A pointer to the first node in the list. Each node contains a pointer to the next node in the list The last node contains a null pointer As a variation first may be a structure also contain a count of the elements in the list 15
16
Array-Based Implementation of Linked Lists Given a list with names Implementation would look like this 16
17
Chapter Contents 11.1 Some Variants of Singly-Linked Lists 11.2 Linked Implementation of Sparse Polynomials 11.3 Doubly-Linked Lists and the Standard C++ list 11.4 Case Study: Larger-Integer Arithmetic 11.5 Other Multiply-Linked Lists 17
18
Chapter Objectives Survey common variants of linked lists and why they are used Describe doubly-linked lists and how they are used to implement C++ STL list container Look briefly at some other applications of multiply-linked lists 18
19
Linked Lists with Head Nodes Consider linked lists from Chapter 6 First node is different from others Has no predecessor Thus insertions and deletions must consider two cases First node or not first node The algorithm is different for each 19
20
Linked Lists with Head Nodes Dual algorithms can be reduced to one Create a "dummy" head node Serves as predecessor holding actual first element Thus even an empty list has a head node 20
21
Linked Lists with Head Nodes For insertion at beginning of list Head node is predecessor for new node newptr->next = predptr->next; predptr->next = newptr; 21
22
Linked Lists with Head Nodes For deleting first element from a list with a head node Head node is the predecessor predptr->next = ptr->next; delete ptr; 22
23
Circular Linked Lists Set the link in last node to point to first node Each node now has both predecessor and successor Insertions, deletions now easier Special consideration required for insertion to empty list, deletion from single item list 23
24
Circular Linked Lists Traversal algorithm must be adjusted (first != 0) // list not empty { ptr = first; do { // process ptr->data ptr = ptr->next; } while (ptr != first); } A do-while loop must be used instead of a while loop Why is this required? 24
25
Doubly-Linked Lists Bidirectional lists Nodes have data part, forward and backward link Facilitates both forward and backward traversal Requires pointers to both first and last nodes 25
26
Doubly-Linked Lists To insert a new node Set forward and backward links to point to predecessor and successor Then reset forward link of predecessor, backward link of successor 26
27
Doubly-Linked Lists To delete a node Reset forward link of predecessor, backward link of successor Then delete removed node 27
28
The STL list Class Template A sequential container Optimized for insertion and erasure at arbitrary points in the sequence. Implemented as a circular doubly-linked list with head node. 28
29
Comparing List With Other Containers Note : list does not support direct access does not have the subscript operator [ ] 29 PropertyArray vector deque list Direct/random access ( [] ) Excellent Excellent Good NA Sequential access Excellent Excellent Good Excellent Insert/delete at front Poor Poor Excellent Excellent Insert/delete in middle Poor Poor Poor Excellent Insert/delete at end Excellent Excellent Excellent Excellent Overheadlowestlowlow/mediumhigh
30
list Iterators list 's iterator is "weaker" than that for vector vector : random access iterators list : bidirectional iterators Operations in common ++Move iterator to next element (like ptr = ptr-> next ) --Move iterator to preceding element (like ptr = ptr-> prev ) *dereferencing operator (like ptr-> data ) 30
31
list Iterators Operators in common =assignment (for same type iterators) it1 = it2 makes it1 positioned at same element as it2 == and != (for same type iterators) checks whether iterators are positioned at the same element See basic list operations, Table 11-2 View demonstration of list operations, Fig. 11-1Fig. 11-1 31
32
Example: Internet Addresses Consider a program that stores IP addresses of users who make a connection with a certain computer We store the connections in an AddressCounter object Tracks unique IP addresses and how many times that IP connected View source code, Fig. 11.2Fig. 11.2 Note uses of STL list and operators 32
33
The STL list Class Template Node structure struct list_node { pointer next, prev; T data; } 33
34
The STL list Class Template But it's allo/deallo-cation scheme is complex Does not simply using new and delete operations. Using the heap manager is inefficient for large numbers of allo/deallo-cations Thus it does it's own memory management. 34
35
The STL list Memory Management When a node is allocated 1.If there is a node on the free list, allocate it. This is maintained as a linked stack 2.If the free list is empty: a)Call the heap manager to allocate a block of memory (a "buffer", typically 4K) b)Carve it up into pieces of size required for a node of a list 35
36
The STL list Memory Management When a node is deallocated Push it onto the free list. When all lists of this type T have been destroyed Return it to the heap 36
37
Multiply-Ordered Lists Ordered linked list Nodes arranged so data items are in ascending/descending order Straightforward when based on one data field However, sometimes necessary to maintain links with a different ordering Possible solution Separate ordered linked lists – but wastes space 37
38
Multiply-Ordered Lists Better approach Single list Multiple links 38
39
Sparse Matrices Usual storage is 2D array or 2D vector If only a few nonzero entries Can waste space Stored more efficiently with linked structure Similar to sparse polynomials Each row is a linked list Store only nonzero entries for the row 39
40
Sparse Matrices For we represent with 40 A =
41
Sparse Matrices This still may waste space Consider if many rows were all zeros Alternative implementation Single linked list Each node has row, column, entry, link Resulting list 41 A =
42
Sparse Matrices However … this loses direct access to rows Could replace array of pointers with Linked list of row head nodes Each contains pointer to non empty row list 42 A =
43
Sparse Matrices If columnwise processing is desired Use orthogonal list Each node stores row, column, value, pointer to row successor, pointer to column successor Each row list and column list is a circular list with a head node These head nodes are linked together to form another circular list with a “master” head node 43
44
Sparse Matrices Note the resulting representation of the matrix 44 A =
45
Generalized Lists Examples so far have had atomic elements The nodes are not themselves lists Generalized List: a list where the elements themselves are lists Consider a linked list of strings The strings themselves can be linked lists of characters 45 This is an example of a generalized list
46
Generalized Lists Commonly represented as linked lists where Nodes have a tag field along with data and link Tag used to indicate whether data field holds Atom Pointer to a list 46
47
Generalized Lists Lists can be shared To represent (2, (4,6), (4,6)) For polynomials in two variables P(x,y) = 3 + 7x + 14y 2 + 25y 7 – 9x 2 y 7 + 18x 6 y 7 P(x,y) = (3 + 7x) + 14y 2 + (25 – 9x 2 + 18x 6 )y 7 47
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.