Chapter 4 Linked Lists. © 2005 Pearson Addison-Wesley. All rights reserved4-2 Preliminaries Options for implementing an ADT List –Array has a fixed size.

Slides:



Advertisements
Similar presentations
Numbers Treasure Hunt Following each question, click on the answer. If correct, the next page will load with a graphic first – these can be used to check.
Advertisements

Chapter 25 Lists, Stacks, Queues, and Priority Queues
TK1924 Program Design & Problem Solving Session 2011/2012
AP STUDY SESSION 2.
1
Copyright © 2003 Pearson Education, Inc. Slide 1.
Chapter 7 Constructors and Other Tools. Copyright © 2006 Pearson Addison-Wesley. All rights reserved. 7-2 Learning Objectives Constructors Definitions.
Chapter 17 Linked Data Structures. Copyright © 2006 Pearson Addison-Wesley. All rights reserved Learning Objectives Nodes and Linked Lists Creating,
Copyright © 2003 Pearson Education, Inc. Slide 1 Computer Systems Organization & Architecture Chapters 8-12 John D. Carpinelli.
Copyright © 2011, Elsevier Inc. All rights reserved. Chapter 6 Author: Julia Richards and R. Scott Hawley.
David Burdett May 11, 2004 Package Binding for WS CDL.
Local Customization Chapter 2. Local Customization 2-2 Objectives Customization Considerations Types of Data Elements Location for Locally Defined Data.
1 10 pt 15 pt 20 pt 25 pt 5 pt 10 pt 15 pt 20 pt 25 pt 5 pt 10 pt 15 pt 20 pt 25 pt 5 pt 10 pt 15 pt 20 pt 25 pt 5 pt 10 pt 15 pt 20 pt 25 pt 5 pt BlendsDigraphsShort.
Break Time Remaining 10:00.
Turing Machines.
Table 12.1: Cash Flows to a Cash and Carry Trading Strategy.
PP Test Review Sections 6-1 to 6-6
Chapter 17 Linked Lists.
COMP171 Fall 2005 Lists.
Lists Chapter 6 Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights reserved
DATA STRUCTURES AND ALGORITHMS Prepared by İnanç TAHRALI
Linked Lists Chapter 4.
Data Structures: A Pseudocode Approach with C
Data Structures ADT List
Chapter 24 Lists, Stacks, and Queues
Main Index Contents 11 Main Index Contents Shifting blocks of elements… Shifting blocks of elements… Model of a list object… Model of a list object… Sample.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley. Ver Chapter 4: Linked Lists Data Abstraction & Problem Solving with.
Alan YorinksLecture 7 1 • Tonight we will look at:: • List ADT • Unsorted List • Sequential Search • Selection Sort • Sorted List • Binary Search.
Data Structures Using C++
Data Structures Part 2 Stacks, Queues, Trees, and Graphs Briana B. Morrison CSE 1302C Spring 2010.
Double-Linked Lists and Circular Lists
Chapter 1 Object Oriented Programming 1. OOP revolves around the concept of an objects. Objects are created using the class definition. Programming techniques.
CSE Lecture 12 – Linked Lists …
2000 Deitel & Associates, Inc. All rights reserved. Chapter 16 – Bits, Characters, Strings, and Structures Outline 16.1Introduction 16.2Structure Definitions.
Bellwork Do the following problem on a ½ sheet of paper and turn in.
Exarte Bezoek aan de Mediacampus Bachelor in de grafische en digitale media April 2014.
Copyright © 2012, Elsevier Inc. All rights Reserved. 1 Chapter 7 Modeling Structure with Blocks.
Adding Up In Chunks.
Copyright © 2013 by John Wiley & Sons. All rights reserved. HOW TO CREATE LINKED LISTS FROM SCRATCH CHAPTER Slides by Rick Giles 16 Only Linked List Part.
1 10 pt 15 pt 20 pt 25 pt 5 pt 10 pt 15 pt 20 pt 25 pt 5 pt 10 pt 15 pt 20 pt 25 pt 5 pt 10 pt 15 pt 20 pt 25 pt 5 pt 10 pt 15 pt 20 pt 25 pt 5 pt Synthetic.
© 2010 Pearson Addison-Wesley. All rights reserved. Addison Wesley is an imprint of CHAPTER 11: Priority Queues and Heaps Java Software Structures: Designing.
1 hi at no doifpi me be go we of at be do go hi if me no of pi we Inorder Traversal Inorder traversal. n Visit the left subtree. n Visit the node. n Visit.
Speak Up for Safety Dr. Susan Strauss Harassment & Bullying Consultant November 9, 2012.
Essential Cell Biology
Clock will move after 1 minute
PSSA Preparation.
Essential Cell Biology
Immunobiology: The Immune System in Health & Disease Sixth Edition
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 13 Pointers and Linked Lists.
Physics for Scientists & Engineers, 3rd Edition
Energy Generation in Mitochondria and Chlorplasts
Select a time to count down from the clock above
1 Decidability continued…. 2 Theorem: For a recursively enumerable language it is undecidable to determine whether is finite Proof: We will reduce the.
Chapter 4 Linked Lists. © 2005 Pearson Addison-Wesley. All rights reserved4-2 Preliminaries Options for implementing an ADT List –Array has a fixed size.
Chapter 4 Linked Lists. © 2005 Pearson Addison-Wesley. All rights reserved4-2 Preliminaries Options for implementing an ADT List –Array has a fixed size.
2 Preliminaries Options for implementing an ADT List Array has a fixed size Data must be shifted during insertions and deletions Linked list is able to.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley. Ver Chapter 4: Linked Lists Data Abstraction & Problem Solving with.
© 2006 Pearson Addison-Wesley. All rights reserved5 B-1 Chapter 5 (continued) Linked Lists.
Chapter 5 Linked Lists. © 2004 Pearson Addison-Wesley. All rights reserved 5 A-2 Preliminaries Options for implementing an ADT –Array Has a fixed size.
Data Abstraction and Problem Solving with C++ Walls and Mirrors, Third Edition, Frank M. Carrano and Janet J. Prichard ©2002 Addison Wesley CHAPTER 4 Linked.
CC 215 DATA STRUCTURES LINKED LISTS Dr. Manal Helal - Fall 2014 Lecture 3 AASTMT Engineering and Technology College 1.
1 Linked List. List vs Arrays Two built-in data structures that can be used to organize data, or to create other data structures: Lists Arrays.
Chapter 4 Linked Lists.
Chapter 4 Linked Lists
Linked Lists Chapter 4.
Chapter 4 Linked Lists.
Linked Lists Chapter 4.
Chapter 4 Linked Lists.
Linked Lists Chapter 5 (continued)
Presentation transcript:

Chapter 4 Linked Lists

© 2005 Pearson Addison-Wesley. All rights reserved4-2 Preliminaries Options for implementing an ADT List –Array has a fixed size Data must be shifted during insertions and deletions –Linked list is able to grow in size as needed Does not require the shifting of items during insertions and deletions

© 2005 Pearson Addison-Wesley. All rights reserved4-3 Preliminaries Figure 4.1 a) A linked list of integers; b) insertion; c) deletion

© 2005 Pearson Addison-Wesley. All rights reserved4-4 Pointer-Based Linked Lists A node in a linked list is usually a struct struct Node{ int item; Node *next; }; A node is dynamically allocated Node *p; p = new Node; Figure 4.6 A node

© 2005 Pearson Addison-Wesley. All rights reserved4-5 Pointer-Based Linked Lists The head pointer points to the first node in a linked list If head is NULL, the linked list is empty

© 2005 Pearson Addison-Wesley. All rights reserved4-6 Pointer-Based Linked Lists Figure 4.7 A head pointer to a list Figure 4.8 A lost cell

© 2005 Pearson Addison-Wesley. All rights reserved4-7 Displaying the Contents of a Linked List Reference a node member with the -> operator p->item; A traverse operation visits each node in the linked list –A pointer variable cur keeps track of the current node for (Node *cur = head; cur != NULL; cur = cur->next) cout item << endl;

© 2005 Pearson Addison-Wesley. All rights reserved4-8 Displaying the Contents of a Linked List Figure 4.9 The effect of the assignment cur = cur->next

© 2005 Pearson Addison-Wesley. All rights reserved4-9 Deleting a Specified Node from a Linked List Deleting an interior node prev->next=cur->next; Deleting the first node head=head->next; Return deleted node to system cur->next = NULL; delete cur; cur=NULL;

© 2005 Pearson Addison-Wesley. All rights reserved4-10 Deleting a Specified Node from a Linked List Figure 4.10 Deleting a node from a linked list Figure 4.11 Deleting the first node

© 2005 Pearson Addison-Wesley. All rights reserved4-11 Inserting a Node into a Specified Position of a Linked List To insert a node between two nodes newPtr->next = cur; prev->next = newPtr; Figure 4.12 Inserting a new node into a linked list

© 2005 Pearson Addison-Wesley. All rights reserved4-12 Inserting a Node into a Specified Position of a Linked List To insert a node at the beginning of a linked list newPtr->next = head; head = newPtr; Figure 4.13 Inserting at the beginning of a linked list

© 2005 Pearson Addison-Wesley. All rights reserved4-13 Inserting a Node into a Specified Position of a Linked List Inserting at the end of a linked list is not a special case if cur is NULL newPtr->next = cur; prev->next = newPtr; Figure 4.14 Inserting at the end of a linked list

© 2005 Pearson Addison-Wesley. All rights reserved4-14 Inserting a Node into a Specified Position of a Linked List Determining the point of insertion or deletion for a sorted linked list of objects for(prev = NULL, cur= head; (cur != null)&& (newValue > cur->item); prev = cur, cur = cur->next);

© 2005 Pearson Addison-Wesley. All rights reserved4-15 A Pointer-Based Implementation of the ADT List Public methods –isEmpty –getLength –insert –remove –retrieve Private method –find Private Data Members –head –size Local variables to member functions –cur –prev

© 2005 Pearson Addison-Wesley. All rights reserved4-16 Constructors and Destructors Default constructor initializes size and head Copy constructor allows a deep copy –Copies the array of list items and the number of items A destructor is required for dynamically allocated memory

© 2005 Pearson Addison-Wesley. All rights reserved4-17 A Pointer-Based Implementation of the ADT List // **************************************** // Header file ListP.h for the ADT list. // Pointer-based implementation. //***************************************** typedef desired-type-of-list-item ListItemType; class List{ // constructors and destructor: public: List(); // default constructor List(const List& aList); // copy constructor ~List(); // destructor

© 2005 Pearson Addison-Wesley. All rights reserved4-18 A Pointer-Based Implementation of the ADT List // list operations: bool isEmpty() const; int getLength() const; bool insert(int index, ListItemType newItem); bool remove(int index); bool retrieve(int index, ListItemType& dataItem) const;

© 2005 Pearson Addison-Wesley. All rights reserved4-19 A Pointer-Based Implementation of the ADT List private: struct ListNode{ // a node on the list ListItemType item; // a data item on the list ListNode *next; // pointer to next node }; int size; // number of items in list ListNode *head; // pointer to linked list // of items ListNode *find(int index) const; // Returns a pointer to the index-th node // in the linked list. };

© 2005 Pearson Addison-Wesley. All rights reserved4-20 A Pointer-Based Implementation of the ADT List // ********************************************** // Implementation file ListP.cpp for the ADT list // Pointer-based implementation. // ********************************************** #include "ListP.h" // header file #include // for NULL List::List(): size(0), head(NULL){ }

© 2005 Pearson Addison-Wesley. All rights reserved4-21 A Pointer-Based Implementation of the ADT List List::List(const List& aList): size(aList.size){ if (aList.head == NULL) head = NULL; // original list is empty else { // copy first node head = new ListNode; head->item = aList.head->item; // copy rest of list ListNode *newPtr = head; // new list ptr for (ListNode *origPtr = aList.head->next; origPtr != NULL; origPtr = origPtr->next){ newPtr->next = new ListNode; newPtr = newPtr->next; newPtr->item = origPtr->item; } newPtr->next = NULL; } } // end copy constructor

© 2005 Pearson Addison-Wesley. All rights reserved4-22 A Pointer-Based Implementation of the ADT List List::~List(){ while (!isEmpty()) remove(1); } // end destructor

© 2005 Pearson Addison-Wesley. All rights reserved4-23 A Pointer-Based Implementation of the ADT List bool List::isEmpty() const{ return size == 0; } // end isEmpty

© 2005 Pearson Addison-Wesley. All rights reserved4-24 A Pointer-Based Implementation of the ADT List int List::getLength() const{ return size; } // end getLength

© 2005 Pearson Addison-Wesley. All rights reserved4-25 A Pointer-Based Implementation of the ADT List List::ListNode *List::find(int index) const{ // Locates a specified node in a linked list. // Precondition: index is the number of the // desired node. // Postcondition: Returns a pointer to the // desired node. If index the // number of nodes in the list, returns NULL. if ( (index getLength()) ) return NULL; else{ // count from the beginning of the list ListNode *cur = head; for (int skip = 1; skip < index; ++skip) cur = cur->next; return cur; } } // end find

© 2005 Pearson Addison-Wesley. All rights reserved4-26 A Pointer-Based Implementation of the ADT List bool List::retrieve(int index, ListItemType& dataItem) const { if ((index getLength())) return false; // get pointer to node, then data in node ListNode *cur = find(index); dataItem = cur->item; return true; } // end retrieve

© 2005 Pearson Addison-Wesley. All rights reserved4-27 A Pointer-Based Implementation of the ADT List bool List::insert(int index, ListItemType newItem) { int newLength = getLength() + 1; if ((index newLength)) return false; ListNode *newPtr = new ListNode; size = newLength; newPtr->item = newItem; if (index == 1){ newPtr->next = head; head = newPtr; } else{ ListNode *prev = find(index-1); newPtr->next = prev->next; prev->next = newPtr; } return true; } // end insert

© 2005 Pearson Addison-Wesley. All rights reserved4-28 A Pointer-Based Implementation of the ADT List bool List::remove(int index) { ListNode *cur; if ((index getLength())) return false; --size; if (index == 1){ cur = head; head = head->next; } else{ ListNode *prev = find(index-1); cur = prev->next; prev->next = cur->next; } cur->next = NULL; delete cur; cur = NULL; return true; } // end remove

© 2005 Pearson Addison-Wesley. All rights reserved4-29 Comparing Array-Based and Pointer-Based Implementations Size –Increasing the size of a resizable array can waste storage and time Storage requirements –Array-based implementations require less memory than a pointer-based ones

© 2005 Pearson Addison-Wesley. All rights reserved4-30 Comparing Array-Based and Pointer-Based Implementations Access time –Array-based: constant access time –Pointer-based: the time to access the i th node depends on i Insertion and deletions –Array-based: require shifting of data –Pointer-based: require a list traversal

© 2005 Pearson Addison-Wesley. All rights reserved4-31 Saving and Restoring a Linked List by Using a File Use an external file to preserve the list between runs Do not write pointers to a file, only data Recreate the list from the file by placing each item at the end of the list –Use a tail pointer to facilitate adding nodes to the end of the list –Treat the first insertion as a special case by setting the tail to head

© 2005 Pearson Addison-Wesley. All rights reserved4-32 Saving and Restoring a Linked List by Using a File // Saves a linked list's data in a text file of // integers; head points to the linked list. // fileName is a string that names an external text // file to be created ofstream outFile(fileName); // traverse the list to the end, writing each item for (Node *cur = head; cur != NULL; cur = cur->next) outFile item << endl; outFile.close(); // Assertion: The text file contains the linked // lists data in its original order.

© 2005 Pearson Addison-Wesley. All rights reserved4-33 Saving and Restoring a Linked List by Using a File // Creates a linked list from the data in a text file. The // pointer variables head and tail are initially NULL. fileName // is a string that names an existing external text file. Node *head = NULL, *tail = NULL; ifstream inFile(fileName); int nextItem; if (inFile >> nextItem){ head = new Node; head->item = nextItem; head->next = NULL; tail = head; // Assertion: head points to while (inFile >> nextItem){ // the first node of the tail->next = new Node; // created linked list; tail tail = tail->next; // points to the last node. tail->item = nextItem; // If the file is empty, head tail->next = NULL; // and tail are NULL (list is } // empty). } inFile.close();

© 2005 Pearson Addison-Wesley. All rights reserved4-34 Passing a Linked List to a Function A function with access to a linked lists head pointer has access to the entire list Pass the head pointer to a function as a reference argument Figure 4.22 A head pointer as a value argument

© 2005 Pearson Addison-Wesley. All rights reserved4-35 Processing Linked Lists Recursively Recursive strategy to display a list –Write the first node of the list –Write the list minus its first node

© 2005 Pearson Addison-Wesley. All rights reserved4-36 Processing Linked Lists Recursively void writeString(Node *stringPtr){ if (stringPtr != NULL){ // write the first character cout item; // write the string minus its // first character writeString(stringPtr->next); } } // end writeString

© 2005 Pearson Addison-Wesley. All rights reserved4-37 Processing Linked Lists Recursively Recursive strategies to display a list backward –writeBackward strategy Write the last node of the list Write the list minus its last node backward

© 2005 Pearson Addison-Wesley. All rights reserved4-38 Processing Linked Lists Recursively Recursive strategies to display a list backward –writeBackward2 strategy Write the list minus its first node backward Write the first node of the list

© 2005 Pearson Addison-Wesley. All rights reserved4-39 Processing Linked Lists Recursively void writeBackward2(Node *stringPtr){ if (stringPtr != NULL){ // write the string minus its first // character backward writeBackward2(stringPtr->next); // write the first character cout item; } } // end writeBackward2

© 2005 Pearson Addison-Wesley. All rights reserved4-40 Processing Linked Lists Recursively Recursive view of a sorted linked list –The linked list to which head points is a sorted list if head is NULL or head->next is NULL or head->item next->item, and head->next points to a sorted linked list

© 2005 Pearson Addison-Wesley. All rights reserved4-41 Processing Linked Lists Recursively void linkedListInsert(Node *& headPtr, ListItemType newItem){ if ((headPtr == NULL) || (newItem item)){ // base case: insert newItem at // beginning of the linked list to // which headPtr points Node *newPtr = new Node; newPtr->item = newItem; newPtr->next = headPtr; headPtr = newPtr; } else linkedListInsert(headPtr->next,newItem); } // end linkedListInsert

© 2005 Pearson Addison-Wesley. All rights reserved4-42 Objects as Linked List Data Data in a linked list node can be an instance of a class typedef ClassName ItemType; struct Node{ ItemType item; Node *next; }; Node *head;

© 2005 Pearson Addison-Wesley. All rights reserved4-43 Circular Linked Lists Last node references the first node Every node has a successor No node in a circular linked list contains NULL Figure 4.25 A circular linked list

© 2005 Pearson Addison-Wesley. All rights reserved4-44 Circular Linked Lists Figure 4.26 A circular linked list with an external pointer to the last node

© 2005 Pearson Addison-Wesley. All rights reserved4-45 Circular Linked Lists // display the data in a circular linked list; // list points to its last node if (list != NULL){ // list is not empty Node *first = list->next; // point to first node Node *cur = first; // start at first node // Loop invariant: cur points to next node to // display do{ display(cur->item); // write data portion cur = cur->next; // point to next node } while (cur != first); // list traversed? }

© 2005 Pearson Addison-Wesley. All rights reserved4-46 Dummy Head Nodes Dummy head node –Always present, even when the linked list is empty –Insertion and deletion algorithms initialize prev to reference the dummy head node, rather than NULL Figure 4.27 A dummy head node

© 2005 Pearson Addison-Wesley. All rights reserved4-47 Doubly Linked Lists Each node points to both its predecessor and its successor Circular doubly linked list –precede pointer of the dummy head node points to the last node –next reference of the last node points to the dummy head node –No special cases for insertions and deletions

© 2005 Pearson Addison-Wesley. All rights reserved4-48 Doubly Linked Lists Figure 4.28 A doubly linked list

© 2005 Pearson Addison-Wesley. All rights reserved4-49 Doubly Linked Lists Figure 4.29 (a) A circular doubly linked list with a dummy head node (b) An empty list with a dummy head node

© 2005 Pearson Addison-Wesley. All rights reserved4-50 Doubly Linked Lists To delete the node to which cur points (cur->precede)->next = cur->next; (cur->next)->precede = cur->precede; To insert a new node pointed to by newPtr before the node pointed to by cur newPtr->next = cur; newPtr->precede = cur->precede; cur->precede = newPtr; newPtr->precede->next = newPtr;

© 2005 Pearson Addison-Wesley. All rights reserved4-51 Summary Each pointer in a linked list is a pointer to the next node in the list Algorithms for insertions and deletions in a linked list involve traversing the list and performing pointer changes –Inserting a node at the beginning of a list and deleting the first node of a list are special cases

© 2005 Pearson Addison-Wesley. All rights reserved4-52 Summary Recursion can be used to perform operations on a linked list In a circular linked list, the last node points to the first node Dummy head nodes eliminate the special cases for insertion into and deletion from the beginning of a linked list