 2006 Pearson Education, Inc. All rights reserved. 1 21 Data Structures.

Slides:



Advertisements
Similar presentations
Linked Lists Geletaw S..
Advertisements

DATA STRUCTURES USING C++ Chapter 5
Linked List 1. Introduction to Linked List 2. Node Class 3. Linked List 4. The Bag Class with Linked List.
Linked Lists CENG 213 Data Structures.
Nirmalya Roy School of Electrical Engineering and Computer Science Washington State University Cpt S 122 – Data Structures Data Structures.
1 Linked List (II) Ying Wu Electrical Engineering & Computer Science Northwestern University EECS 230 Lectures Series.
 2000 Deitel & Associates, Inc. All rights reserved. Chapter 15 – Data Structures Outline 15.1Introduction 15.2Self-Referential Classes 15.3Dynamic Memory.
Chapter 12 C Data Structures Acknowledgment The notes are adapted from those provided by Deitel & Associates, Inc. and Pearson Education Inc.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Chapter 12 – Data Structures Outline 12.1Introduction.
 2003 Prentice Hall, Inc. All rights reserved. 1 Chapter 20 - Data Structures Outline 20.1 Introduction 20.2 Self-Referential Classes 20.3 Dynamic Memory.
C++ Programming: Program Design Including Data Structures, Fifth Edition Chapter 17: Linked Lists.
 2006 Pearson Education, Inc. All rights reserved Data Structures.
Linked List (I) Ying Wu Electrical & Computer Engineering Northwestern University ECE230 Lectures Series.
Chapter 12 Data Structure Associate Prof. Yuh-Shyan Chen Dept. of Computer Science and Information Engineering National Chung-Cheng University.
 2003 Prentice Hall, Inc. All rights reserved Linked Lists Upcoming program has two class templates –Create two class templates –ListNode data.
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.
Nirmalya Roy School of Electrical Engineering and Computer Science Washington State University Cpt S 122 – Data Structures Custom Templatized Data Structures.
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with C++ Early Objects Seventh Edition by Tony Gaddis, Judy.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley. Ver Chapter 4: Linked Lists Data Abstraction & Problem Solving with.
 2006 Pearson Education, Inc. All rights reserved Data Structures.
C++ How to Program, 7/e © by Pearson Education, Inc. All Rights Reserved.
 2007 Pearson Education, Inc. All rights reserved C Data Structures.
C++ Classes and Data Structures Jeffrey S. Childs
Introduction to Data Structures Systems Programming.
1 Chapter 16-1 Linked Structures Dale/Weems. 2 Chapter 16 Topics l Meaning of a Linked List l Meaning of a Dynamic Linked List l Traversal, Insertion.
 2008 Pearson Education, Inc. All rights reserved. 1 Member data stores a value of type parameter NODETYPE Member nextPtr stores a pointer to the next.
Self-Referential Classes A Self-referential class is a class that contains a reference to an object that has the same class type. –A self-referential class.
Introduction to Data Structures Systems Programming Concepts.
C++ Programming: From Problem Analysis to Program Design, Second Edition Chapter 17: Linked Lists.
1 Chapter 16 Linked Structures Dale/Weems. 2 Chapter 16 Topics l Meaning of a Linked List l Meaning of a Dynamic Linked List l Traversal, Insertion and.
1 Chapter 16 Linked Structures Dale/Weems/Headington.
Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights reserved Stacks.
1 Chapter 17 – Data Structures Outline Introduction Self-Referential Classes Dynamic Memory Allocation Linked Lists Stacks Queues Trees.
Lists Chapter 8. 2 Linked Lists As an ADT, a list is –finite sequence (possibly empty) of elements Operations commonly include: ConstructionAllocate &
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide
Copyright © 2012 Pearson Education, Inc. Chapter 17: Linked Lists.
 2003 Prentice Hall, Inc. All rights reserved. 1 Chapter 17 - Data Structures Outline 17.1 Introduction 17.2 Self-Referential Classes 17.3 Dynamic Memory.
Programming Practice 3 - Dynamic Data Structure
Chapter 5 Linked List by Before you learn Linked List 3 rd level of Data Structures Intermediate Level of Understanding for C++ Please.
 2003 Prentice Hall, Inc. All rights reserved. 1 Lecture 6: Classes and Data Abstraction Posted Feb 3 Chapter 6 pointer for function Class Introduction.
1 CISC181 Introduction to Computer Science Dr. McCoy Lecture 20 November 10, 2009.
CS162 - Topic #7 Lecture: Dynamic Data Structures –Review of pointers and the new operator –Introduction to Linked Lists –Begin walking thru examples of.
Chapter 17: Linked Lists. Objectives In this chapter, you will: – Learn about linked lists – Learn the basic properties of linked lists – Explore insertion.
Linked List.  Is a series of connected nodes, where each node is a data structure with data and pointer(s) Advantages over array implementation  Can.
1 Linked List. Outline Introduction Insertion Description Deletion Description Basic Node Implementation Conclusion.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Linked Lists Outline Introduction Self-Referential Structures.
Copyright © 2014, 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with C++ Early Objects Eighth Edition by Tony Gaddis,
CMSC 202 Computer Science II for Majors. CMSC 202UMBC Topics Templates Linked Lists.
Chapter 20 Custom Templatized Data Structures
Linked Lists Chapter 6 Section 6.4 – 6.6
12 C Data Structures.
12 C Data Structures.
Lists CS 3358.
CISC181 Introduction to Computer Science Dr
Intro to Data Structures
Chapter 4 Linked Lists.
Introduction to Data Structures
Chapter 4 Linked Lists
Prof. Neary Adapted from slides by Dr. Katherine Gibson
Chapter 16-2 Linked Structures
Linked Lists.
Chapter 4 Linked Lists.
Review & Lab assignments
Chapter 4 Linked Lists.
Chapter 16 Linked Structures
Data Structures & Algorithms
Intro to OOP with Java, C. Thomas Wu By : Zanariah Idrus
Lists CMSC 202, Version 4/02.
Lists CMSC 202, Version 4/02.
21 Data Structures.
Presentation transcript:

 2006 Pearson Education, Inc. All rights reserved Data Structures

 2006 Pearson Education, Inc. All rights reserved Self-Referential Classes Self-referential class – Contains a pointer member that points to an object of the same class type – Example Class Node { … Node *nextPtr; }; – Pointer data member nextPtr is a link Can tie a Node to another Node

3 Fig | Two self-referential class objects linked together.

 2006 Pearson Education, Inc. All rights reserved Dynamic Memory Allocation and Data Structures Dynamic memory allocation – Enables a program to obtain more memory at execution time That memory can be released when it is no longer needed – Limited by amount of physical or virtual memory Memory must be shared among many programs

Common Programming Error 21.1 Not setting the link in the last node of a linked data structure to null ( 0 ) is a (possibly fatal) logic error.

6 Lets look at lists: Using Arrays fixed size Must shift to add something to the front or delete the first element (or anywhere in the middle) Easy to add at the end Using Vectors Not fixed size Still have to shift to add something

To add an element, one has to shift everything over

8 complexity To add an element to a list of size n: O(n) To delete an element to a list of size n: O(n) Shifting is an expensive operation since it involves a copy. Not practical for large lists! Can we do something else?

 2006 Pearson Education, Inc. All rights reserved Linked Lists Linked list – Linear collection of self-referential class objects Called nodes Connected by pointer links – Accessed via a pointer to the first node Subsequent nodes are accessed via previous node’s link – By convention, link in last node is set to null pointer 0 – Additional nodes are dynamically allocated as necessary

 2006 Pearson Education, Inc. All rights reserved Linked Lists (Cont.) Linked list (Cont.) – Advantages over arrays Linked lists are dynamic – Length can increase or decrease as necessary Efficient insertion of new elements into a sorted list – Existing list elements do not need to be moved

Performance Tip 21.1 An array can be declared to contain more elements than the number of items expected, but this can waste memory. Linked lists can provide better memory utilization in these situations. Linked lists allow the program to adapt at runtime. Note that class template vector (introduced in Section 7.11) implements a dynamically resizable array- based data structure.

Performance Tip 21.2 Insertion and deletion in a sorted array can be time consuming—all the elements following the inserted or deleted element must be shifted appropriately. A linked list allows efficient insertion operations anywhere in the list.

Performance Tip 21.3 The elements of an array are stored contiguously in memory. This allows immediate access to any array element, because the address of any element can be calculated directly based on its position relative to the beginning of the array. Linked lists do not afford such immediate “direct access” to their elements. So accessing individual elements in a linked list can be considerably more expensive than accessing individual elements in an array. The selection of a data structure is typically based on the performance of specific operations used by a program and the order in which the data items are maintained in the data structure. For example, it is typically more efficient to insert an item in a sorted linked list than a sorted array.

Performance Tip 21.4 Using dynamic memory allocation (instead of fixed-size arrays) for data structures that grow and shrink at execution time can save memory. Keep in mind, however, that pointers occupy space and that dynamic memory allocation incurs the overhead of function calls.

alicebarneybatmanrobinsuperman 1 st element 2 nd element 3 rd element 4 th element 5 th element To add an element named “powerranger” alicebarneybatmanrobinsuperman powerranger A graphical representation of a linked list HeadOfList

To delete alice alicebarneybatmanrobinsuperman powerranger HeadOfList

17 Fig | A graphical representation of a list.

18 Using Self Referential classes Same as structs!

19 int main() { ListNode n1(5); ListNode n2(4); n1.nextPtr = &n2; n2.nextPtr = new ListNode (7); ListNode *pp; pp= &n1; for(int I = 0; i<2; i++) { pp=pp->nextPtr; cout getData() <<endl; } class ListNode { public: ListNode( const int & ); // constructor int getData() const; // return data in node // everything is public for this example int data; // data ListNode *nextPtr; // next node in list }; // end class ListNode ListNode::ListNode( const int &info ) : data( info ), nextPtr( 0 ) { // empty body } // end ListNode constructor int ListNode::getData() const { return data; } // end function getData

20 int main() { ListNode *p1,* p2*,p3; p1= new ListNode (7); P1->nextPtr=new ListNode(5); P3 = new ListNode(6); P3->nextPtr=p1; ListNode *pp=p3; for(int I = 0; i<2; i++) { cout getData() <<endl; pp=pp->nextPtr; ; }

21 Int data ListNode *nextPtr Holds an address of a ListNode int main() { ListNode n1(5); ListNode n2(4); n1.nextPtr = &n2; n2.nextPtr = new ListNode (7); ListNode *pp; pp= &n1; for(int I = 0; i<2; i++) { pp=pp->nextPtr; cout getData() <<endl; }

22 Have a class That includes the listnode class and that has all the functions of a list: insertAtFront insertAtBack removeFromFront RemoveFromBack Etc….

23 Problem: Listnode has everything public Let the new class LIST be a friend of listnode and make listnode private.

24 class List; class ListNode { friend class List; // make List a friend public: ListNode( const int & ); // constructor int getData() const; // return data in node private: int data; // data ListNode *nextPtr; // next node in list }; // end class ListNode ListNode::ListNode( const int &info ) : data( info ), nextPtr( 0 ) { // empty body } // end ListNode constructor int ListNode::getData() const { return data; } // end function getData File: ListNode.h NOTE FORWARD DECLARATION HERE SO that when the statement “ friend class List ” is encountered the compiler knows that the definition for class List will be coming …..

25 #include using std::cout; #include "ListnodeINT.h" // ListNode class definition class List { public: List(); // constructor ~List(); // destructor void insertAtFront( const int & ); void insertAtBack( const int & ); bool removeFromFront( int & ); bool removeFromBack( int & ); bool isEmpty() const; void print() const; private: ListNode *firstPtr; // pointer to first node ListNode *lastPtr; // pointer to last node -- optional // utility function to allocate new node ListNode *getNewNode( const int& ); }; // end class List

26 constructor List::List() : firstPtr( 0 ), lastPtr( 0 ) { // empty body } // end List constructor

27 isempty bool List::isEmpty() const { return firstPtr == 0; } // end function isEmpty

28 ListNode getnewNode(const in &value) ListNode *List::getNewNode(const int &value ) { return new ListNode( value ); } // end function getNewNode

29 insertAtFront(const int &value) void List::insertAtFront( const int &value ) { ListNode *newPtr = getNewNode( value ); // new node if ( isEmpty() ) // List is empty firstPtr = lastPtr = newPtr; // new list has only one node else // List is not empty { newPtr->nextPtr = firstPtr; // point new node to previous 1st node firstPtr = newPtr; // aim firstPtr at new node } // end else } // end function insertAtFront

30 insertAtBack void List::insertAtBack( const int &value ) { ListNode *newPtr = getNewNode( value ); // new node if ( isEmpty() ) // List is empty firstPtr = lastPtr = newPtr; // new list has only one node else // List is not empty { lastPtr->nextPtr = newPtr; // update previous last node lastPtr = newPtr; // new last node } // end else } // end function insertAtBack

31 bool removeFromFront(int &value) bool List::removeFromFront( int &value ) { if ( isEmpty() ) // List is empty return false; // delete unsuccessful else { ListNode *tempPtr = firstPtr; // hold tempPtr to delete if ( firstPtr == lastPtr ) firstPtr = lastPtr = 0; // no nodes remain after removal else firstPtr = firstPtr->nextPtr; // point to previous 2nd node value = tempPtr->data; // return data being removed delete tempPtr; // reclaim previous front node return true; // delete successful } // end else } // end function removeFromFront

32 removeFromBack bool List::removeFromBack( int &value ) { if ( isEmpty() ) // List is empty return false; // delete unsuccessful else { ListNode *tempPtr = lastPtr; // hold tempPtr to delete if ( firstPtr == lastPtr ) // List has one element firstPtr = lastPtr = 0; // no nodes remain after removal else { ListNode *currentPtr = firstPtr; // locate second-to-last element while ( currentPtr->nextPtr != lastPtr ) currentPtr = currentPtr->nextPtr; // move to next node lastPtr = currentPtr; // remove last node currentPtr->nextPtr = 0; // this is now the last node } // end else value = tempPtr->data; // return value from old last node delete tempPtr; // reclaim former last node return true; // delete successful } // end else } // end function removeFromBack

33 print void List::print() const { if ( isEmpty() ) // List is empty { cout << "The list is empty\n\n"; return; } // end if ListNode *currentPtr = firstPtr; cout << "Am at print The list is: "; while ( currentPtr != 0 ) // get element data { cout data << ' '; currentPtr = currentPtr->nextPtr; } // end while cout << "\n\n"; } // end function print

34 Using the list in a main program Can use the same program as before with the array list!!!!!

35 #include “ListI.h” int main() { List alist; bool success; alist.insertAtFront(1); alist.insertAtFront(2); alist.insertAtFront(3); //list is alist.insertAtBack(4); //list is now alist.print(); int a[100]; alist.copylisttoarray(a); for (int i= 0; i< 4; i++) cout <<a[i];

36 An example of data hiding The list is an abstract data type --- the implementation can be hidden from its use!

37 Write a menu based main program which asks the user what they want to do with the list and then performs that action…..

38 What happens with this code? int main() { // test List of int values List integerList; List int2list; for (int i = 0; i < 10; i++) integerList.insertAtFront(i); int2list = integerList; cout << "testing original" << endl; integerList.print(); cout << "testing copy" << endl; int2list.print(); integerList.insertAtBack(11); cout << "testing original" << endl; integerList.print(); cout << "testing copy" << endl; int2list.print(); }

39 List with Templates

 2006 Pearson Education, Inc. All rights reserved. 40 Outline Listnode.h (1 of 2) Member data stores a value of type parameter NODETYPE Member nextPtr stores a pointer to the next ListNode object in the linked list Declare class List as a friend

 2006 Pearson Education, Inc. All rights reserved. 41 Outline Listnode.h (2 of 2)

 2006 Pearson Education, Inc. All rights reserved. 42 Outline List.h (1 of 7) private data members firsrtPtr (a pointer to the first ListNode in a List ) and lastPtr (a pointer to the last ListNode in a List )

 2006 Pearson Education, Inc. All rights reserved. 43 Outline List.h (2 of 7) Initialize both pointers to 0 (null) Ensure that all ListNode objects in a List object are destroyed when that List object is destroyed

 2006 Pearson Education, Inc. All rights reserved. 44 Outline List.h (6 of 7) Determine whether the List is empty Return a dynamically allocated ListNode object

45 Fig | Operation insertAtFront represented graphically.

46 Insert at front: What if there are none in the list? Make sure the first pointer is set properly. What if there is only one?

47 Outline List.h (3 of 7) Places a new node at the front of the list Use function getNewNode to allocate a new ListNode containing value and assign it to newPtr If the list is empty, then both firstPtr and lastPtr are set to newPtr Thread the new node into the list so that the new node points to the old first node and firstPtr points to the new node

48 Fig | Operation insertAtBack represented graphically.

 2006 Pearson Education, Inc. All rights reserved. 49 Outline List.h (3 of 7) Use function getNewNode to allocate a new listNode containing value and assign it to newPtr If the list is empty, then both firstPtr and lastPtr are set to newPtr Thread the new node into the list so that the old last node points to the new node and lastPtr points to the new node

50 Fig | Operation removeFromFront represented graphically.

 2006 Pearson Education, Inc. All rights reserved. 51 Outline List.h (4 of 7) Removes the front node of the list and copies the node value to the reference parameter Return false if an attempt is made to remove a node from an empty list Save a pointer to the first node, which will be removed If the list has only one element, leave the list empty Set firstPtr to point to the second node (the new first node) Copy the removed node ’ s data to reference parameter value delete the removed node

52 Fig | Operation removeFromBack represented graphically.

 2006 Pearson Education, Inc. All rights reserved. 53 Outline List.h (5 of 7) Removes the back node of the list and copies the node value to the reference parameter Return false if an attempt is made to remove a node from an empty list Save a pointer to the last node, which will be removed If the list has only one element, leave the list empty Assign currentPtr the address of the first node to prepare to “ walk the list ” “ Walk the list ” until currentPtr points to the node before the last node, which will be the new last node Make the currentPtr node the new last node Copy the removed node ’ s data to reference parameter value delete the removed node

 2006 Pearson Education, Inc. All rights reserved. 54 Outline List.h (6 of 7)

 2006 Pearson Education, Inc. All rights reserved. 55 Outline Fig21_05.cpp (1 of 6)

 2006 Pearson Education, Inc. All rights reserved. 56 Outline Fig21_05.cpp (2 of 6)

 2006 Pearson Education, Inc. All rights reserved. 57 Outline Fig21_05.cpp (3 of 6)

 2006 Pearson Education, Inc. All rights reserved. 58 Outline Fig21_05.cpp (4 of 6)

 2006 Pearson Education, Inc. All rights reserved. 59 Outline Fig21_05.cpp (5 of 6)

 2006 Pearson Education, Inc. All rights reserved. 60 Outline Fig21_05.cpp (6 of 6)

Error-Prevention Tip 21.1 Assign null ( 0 ) to the link member of a new node. Pointers should be initialized before they are used.

 2006 Pearson Education, Inc. All rights reserved Linked Lists (Cont.) Linked list (Cont.) – Circular, singly linked list Pointer in last node points back to first node – Doubly linked list Each node has a link to next node and a link to previous node Two “start pointers” – One to first node, one to last node Allows traversals both forward and backward – Circular, doubly linked list Forward link of last node points back to first node Backward link of first node points to last node

63 Fig | Circular, singly linked list.

64 Fig | Doubly linked list.

65 Fig | Circular, doubly linked list.