Presentation is loading. Please wait.

Presentation is loading. Please wait.

21 Data Structures.

Similar presentations


Presentation on theme: "21 Data Structures."— Presentation transcript:

1 21 Data Structures

2 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

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

4 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

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

7 To add an element, one has to shift everything over

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

9 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

10 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

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

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

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

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

15 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

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

17 Fig. 21.2 | 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 <<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

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

21 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

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

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

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

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

39 List with Templates

40 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

41 Outline Listnode.h (2 of 2)

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)

43 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

44 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

45 Fig. 21.6 | Operation insertAtFront represented graphically.

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

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

48 Fig. 21.7 | Operation insertAtBack represented graphically.

49 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

50 Fig. 21.8 | Operation removeFromFront represented graphically.

51 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

52 Fig. 21.9 | Operation removeFromBack represented graphically.

53 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

54 Outline List.h (6 of 7)

55 Outline Fig21_05.cpp (1 of 6)

56 Outline Fig21_05.cpp (2 of 6)

57 Outline Fig21_05.cpp (3 of 6)

58 Outline Fig21_05.cpp (4 of 6)

59 Outline Fig21_05.cpp (5 of 6)

60 Outline Fig21_05.cpp (6 of 6)

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

62 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

63 Fig. 21.10 | Circular, singly linked list.

64 Fig. 21.11 | Doubly linked list.

65 Fig. 21.12 | Circular, doubly linked list.


Download ppt "21 Data Structures."

Similar presentations


Ads by Google