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.
Chapter 12 C Data Structures Acknowledgment The notes are adapted from those provided by Deitel & Associates, Inc. and Pearson Education Inc.
 2006 Pearson Education, Inc. All rights reserved Data Structures.
 2006 Pearson Education, Inc. All rights reserved Data Structures.
Linked List (I) Ying Wu Electrical & Computer Engineering Northwestern University ECE230 Lectures Series.
 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 © 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.
 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.
Lists Chapter 8. 2 Linked Lists As an ADT, a list is –finite sequence (possibly empty) of elements Operations commonly include: ConstructionAllocate &
Chapter 5 Linked List by Before you learn Linked List 3 rd level of Data Structures Intermediate Level of Understanding for C++ Please.
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.
CMSC 202 Computer Science II for Majors. CMSC 202UMBC Topics Templates Linked Lists.
Chapter 16: Linked Lists.
Chapter 20 Custom Templatized Data Structures
C++ Programming:. Program Design Including
Pointers and Linked Lists
Chapter 12 – Data Structures
Pointers and Linked Lists
5.13 Recursion Recursive functions Functions that call themselves
Linked Lists Chapter 6 Section 6.4 – 6.6
12 C Data Structures.
Review Deleting an Element from a Linked List Deletion involves:
12 C Data Structures.
Lists CS 3358.
CSE 143 Linked Lists [Chapter , 8.8] 3/30/98.
CISC181 Introduction to Computer Science Dr
Intro to Data Structures
Chapter 4 Linked Lists.
Linked Lists head One downside of arrays is that they have a fixed size. To solve this problem of fixed size, we’ll relax the constraint that the.
Introduction to Data Structures
Chapter 4 Linked Lists
Prof. Neary Adapted from slides by Dr. Katherine Gibson
Chapter 16-2 Linked Structures
Linked Lists.
Object Oriented Programming COP3330 / CGS5409
Chapter 4 Linked Lists.
Chapter 18: Linked Lists.
Linked List (Part I) Data structure.
[Chapter 4; Chapter 6, pp ] CSC 143 Linked Lists [Chapter 4; Chapter 6, pp ]
Doubly Linked List Implementation
Review & Lab assignments
Chapter 4 Linked Lists.
Chapter 17: Linked Lists.
Chapter 16 Linked Structures
Introduction to C++ Linear Linked Lists
Lists.
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.
Chapter 20 - Data Structures
Data Structures & Programming
Presentation transcript:

21 Data Structures

21.2 Self-Referential Classes 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

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

21.3 Dynamic Memory Allocation and Data Structures 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.

Still have to shift to add something 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

To add an element to a list of size n: O(n) 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?

21.4 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

21.4 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.

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

To delete alice alice barney batman robin superman powerranger HeadOfList HeadOfList alice barney batman robin superman powerranger

Fig. 21.2 | A graphical representation of a list.

Using Self Referential classes Same as structs!

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 <<pp->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

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 <<pp->getData() <<endl; pp=pp->nextPtr; ; }

n2.nextPtr = new ListNode (7); ListNode *pp; pp= &n1; 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 <<pp->getData() <<endl; } Int data ListNode *nextPtr Holds an address of a ListNode

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

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

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…..

List(); // constructor ~List(); // destructor #include <iostream> 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

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

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

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

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

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

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 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

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 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 function removeFromBack

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 << currentPtr->data << ' '; currentPtr = currentPtr->nextPtr; } // end while cout << "\n\n"; } // end function print

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

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

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

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

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); }

List with Templates

Outline (1 of 2) Declare class List< NODETYPE > as a friend Listnode.h (1 of 2) Declare class List< NODETYPE > as a friend Member data stores a value of type parameter NODETYPE Member nextPtr stores a pointer to the next ListNode object in the linked list

Outline Listnode.h (2 of 2)

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)

Outline Initialize both pointers to 0 (null) (2 of 7) List.h (2 of 7) Ensure that all ListNode objects in a List object are destroyed when that List object is destroyed

Outline (6 of 7) Determine whether the List is empty List.h (6 of 7) Determine whether the List is empty Return a dynamically allocated ListNode object

Fig. 21.6 | Operation insertAtFront represented graphically.

What if there are none in the list? 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?

(3 of 7) List.h Outline 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 List.h (3 of 7) 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

Fig. 21.7 | Operation insertAtBack represented graphically.

Outline Use function getNewNode to allocate a new listNode containing value and assign it to newPtr List.h (3 of 7) 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

Fig. 21.8 | Operation removeFromFront represented graphically.

Removes the front node of the list and copies the node value to the reference parameter Outline Return false if an attempt is made to remove a node from an empty list List.h (4 of 7) 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

Fig. 21.9 | Operation removeFromBack represented graphically.

Removes the back node of the list and copies the node value to the reference parameter Outline Return false if an attempt is made to remove a node from an empty list List.h (5 of 7) 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

Outline List.h (6 of 7)

Outline Fig21_05.cpp (1 of 6)

Outline Fig21_05.cpp (2 of 6)

Outline Fig21_05.cpp (3 of 6)

Outline Fig21_05.cpp (4 of 6)

Outline Fig21_05.cpp (5 of 6)

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.

21.4 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

Fig. 21.10 | Circular, singly linked list.

Fig. 21.11 | Doubly linked list.

Fig. 21.12 | Circular, doubly linked list.