Presentation is loading. Please wait.

Presentation is loading. Please wait.

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 13: Pointers and Dynamic Data Structures Problem Solving, Abstraction,

Similar presentations


Presentation on theme: "Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 13: Pointers and Dynamic Data Structures Problem Solving, Abstraction,"— Presentation transcript:

1 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 13: Pointers and Dynamic Data Structures Problem Solving, Abstraction, and Design using C++ 6e by Frank L. Friedman and Elliot B. Koffman

2 2 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Dynamic Data Structures Arrays & structs are static (compile time) Dynamic structures expand as program executes Linked list is example of dynamic data structure Node Pointer Linked list

3 3 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 13.1 Pointers and the new Operator Pointer Variable Declarations –pointer variable of type “pointer to float” –can store the address of a float in p float*p; The new operator creates (allocates memory for) a variable of type float & puts the address of the variable in pointer p p = new float; Dynamic allocation occurs during program execution

4 4 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Pointers Actual address has no meaning for us Form:type*variable; Example:float *p; ? P

5 5 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley new Operator Actually allocates storage Form:new type; new type [n]; Example:new float;

6 6 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Accessing Data with Pointers indirection operator * *p = 15.5; Stores floating value 15.5 in memory location *p - the location pointed to by p 15.5 p

7 7 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Pointer Statements float *p; p = new float; *p = 15.5; cout << “The contents of the memory cell pointed to by p is “ << *p << endl; Output The contents of memory cell pointed to by p is 15.5

8 8 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Pointer Operations Pointers can only contain memory addresses So the following are errors: p = 1000; p = 15.5; Assignment of pointers is valid if q & p are the same pointer type q = p; Also relational operations == and !=

9 9 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Dynamic Allocation of Arrays The statements cin >> size; x = new int[size]; dynamically allocate storage for an array x. The size of x is determined by the data value.

10 10 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Pointers to Arrays The declaration int *x; means that x is a pointer to an integer. If x is an array, *x references x[0].

11 11 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Array Pointers in Functions Function addArray returns the element-by-element sum of its two array arguments. int* addArray(const int *a, const int *b, int size) { int *temp; temp = new int[size]; // allocate array for storage of result for (int i = 0; i < size; i++) { *(temp + i) = *(a + i) + *(b + i); cout << *(temp + i) << endl; } return temp; } The result type int* means that the function result is an array. The first two parameters identify a and b as pointers to arrays. Each parameter references element 0 of its actual array argument.

12 12 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Pointer arithmetic In the for loop with counter i, the statement *(temp + i) = *(a + i) + *(b + i); uses pointer arithmetic to advance *temp, *a, and *b to the ith element of each array. This is equivalent to temp[i] = a[i] + b[i]:

13 13 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Pointers to Structs struct electric { string current; int volts; }; electric *p, *q; p and q are pointers to a struct of type electric

14 14 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Pointers to Structs p = new electric; Allocates storage for struct of type electric and places address into pointer p currentvolts p ??

15 15 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley struct Member Access through a Pointer p ->current = “AC”; p ->volts = 115; Could also be referenced as (*p).current = “AC”; (*p).volts = 115; currentvolts p AC115

16 16 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley struct Member Access through a Pointer Form:p ->m Example:p ->volts cout current volts << endl; Output AC115

17 17 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Pointers and Structs q = new electric; Allocates storage for struct of type electric and places address into pointer q Copy contents of p struct to q struct *q = *p; currentvolts p AC115 currentvolts q AC115

18 18 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Pointers and Structs q ->volts = 220; q = p; currentvolts AC220 q AC 115 AC220 pq->currentq->volts p->currentp->volts q

19 19 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 13.2 Manipulating the Heap When new executes where is struct stored ? Heap –C++ storage pool available to new operator Effect of p = new electric;

20 20 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Figure 13.1 Heap before and after execution of p - new node;

21 21 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Returning Cells to the Heap Operation delete p; Returns cells back to heap for re-use When finished with a pointer, delete it Watch –multiple pointers pointing to same address –only pointers created with new are deleted Form:delete variable; Example:delete p;

22 22 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 13.3 Linked Lists and the list Class Arrange dynamically allocated structures into a new structure called a linked list Think of a set of children’s pop beads –Connecting beads to make a chain –You can move things around and re-connect the chain We use pointers to create the same effect

23 23 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Figure 13.2 Children’s pop beads in a chain

24 24 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Declaring Nodes If a pointer is included in a struct we can connect nodes struct node { string word; int count; node *link; }; node *p, *q, *r;

25 25 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Declaring Nodes Each variable p, q and r can point to a struct of type node, containing members –word(string) –count(int) –link(pointer to a node address) word countlink Struct of type node String Integer Address

26 26 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Connecting Nodes Allocate storage of 2 nodes p = new node; q = new node; Assignment Statements p->word = “hat”; p->count = 2; q->word = “top”; q->count = 3;

27 27 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Figure 13.3 Nodes pointed to by p and q

28 28 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Connecting Nodes Link fields are undefined until assignment p->link = q; –Address of q is stored in link field pointed to by p Accessing elements q->word or p->link->word Null stored at last link field q->link = NULL; or p->link->link = NULL;

29 29 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Figure 13.4 List with two elements

30 30 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Inserting a Node Create and initialize node r = new node; r->word = “the”; r->count = 5; Connect node pointed to by p to node pointed to by r p->link = r; Connect node pointed to by r to node pointed to by q r->link = q;

31 31 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Inserting a New Node in a List

32 32 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Insertion at Head of List OldHead points to original list head oldHead = p; Point p to a new node p = new node; Connect new list head to old list head p->link = oldHead;

33 33 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Figure 13.6 Insertion at the head of a list

34 34 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Insertion at End of List Typically less efficient (usually no pointer to end of the list), but sometimes necessary Attach new node to end of list last->link = new node; Mark end with a NULL (from cstdlib) last->link->link = NULL;

35 35 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Figure 13.7 Insertion at the end of a list

36 36 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Deleting a Node Adjust the link fields to remove a node Disconnect the node pointed to by r from its predecessor p->link = r->link; Disconnect the node pointed to by r from its successor r->link = NULL; Return node to heap delete r;

37 37 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Figure 13.8 Deleting a list node

38 38 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Traversing a List Often need to traverse a list –E.g. print contents of list Start at head and move down a trail of pointers –Typically displaying the various nodes contents as the traversing continues Advance node pointer as you traverse head = head->link; Watch use of reference parameters

39 39 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Listing 13.1 Function printList // File: printList.cpp // Display the list pointed to by head void printList (listNode *head) { while (head != NULL) { cout word count << endl; head = head->link; }

40 40 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Circular Lists and Two Way Lists A circular list is where the last node points back to the first node Two way (doubly linked) list contains two pointers –pointer to next node –pointer to previous node

41 41 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley The list Class C++ STL provides a list container class –Two-way –Can use instead of implementing your own –insert, remove from either end –traverse in either direction –use iterator to traverse

42 42 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Member Functions of list Class int size( ) const T front( ) T back( ) void push_back(const T&) void push_front(const T&) void pop_back(int) void pop_front(int) void insert(iterator, const T&) void remove(const T&)

43 43 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Listing 13.2 Using list class

44 44 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Listing 13.2 Using list class (continued)

45 45 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Listing 13.2 Using list class (continued)

46 46 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 13.4 The Stack Abstract Data Type A stack is a data structure in which only the top element can be accessed LIFO (Last-In First-Out) Operations –push –pop

47 47 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley A Stack of Characters *C+2*C+2 s

48 48 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley The C++ stack Class Must include stack library #include Declare the stack stack stack-name; E.g. stack nameStack; stack s;

49 49 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Some stack Member Functions void push(const T&) T top( ) const void pop( ) bool empty( ) const

50 50 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Example x = s.top( ); // stores ‘*’ into x, stack unchanged s.pop( ); // removes top of stack s.push(‘/’); // adds ‘/’ to top of stack *C+2*C+2 s C+2C+2 s /C+2/C+2 s

51 51 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Implementing a stack Template Class Use linked list or vector –all insertions/deletions from same end only *C+2*C+2 C+2 * s.top stack after insertion of “*” C+2C+2 C+2 s.top stack before insertion

52 52 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Listing 13.4 Header file for template class stackList

53 53 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Listing 13.4 Header file for template class stackList (continued)

54 54 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Listing 13.5 Implementation file for template class stackList

55 55 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Listing 13.5 Implementation file for template class stackList (continued)

56 56 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Listing 13.5 Implementation file for template class stackList (continued)

57 57 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Listing 13.5 Implementation file for template class stackList (continued)

58 58 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 13.5 The Queue ADT List-like structure where items are inserted at one end and removed from the other First-In-First-Out (FIFO) E.g. a customer waiting line

59 59 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Figure 13.12 Queue of customers

60 60 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley The C++ queue Class Must include queue library #include Declare the stack stack queue-name; E.g. stack customers;

61 61 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Member Functions of queue Class void push(const T&) T top( ) const void pop( ) bool empty( ) const int size( ) const

62 62 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Implementing a Queue ADT Implement as linked list Same as stack, except that element at the front of the queue is removed first –need pointer to first list element New elements inserted at rear –need pointer to last list element

63 63 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Listing 13.6 Header file for queue template class

64 64 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Listing 13.6 Header file for queue template class (continued)

65 65 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Listing 13.6 Header file for queue template class (continued)

66 66 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Listing 13.7 Implementation file for queue template class

67 67 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Listing 13.7 Implementation file for queue template class (continued)

68 68 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Listing 13.7 Implementation file for queue template class (continued)

69 69 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Listing 13.7 Implementation file for queue template class (continued)

70 70 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Listing 13.7 Implementation file for queue template class (continued)

71 71 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 13.6 Binary Trees Like a list with additional pointer Nodes contain 2 pointers –right pointer –left pointer –0 (leaf nodes), 1, or 2 successor nodes Binary Tree –empty –root left and right sub-trees

72 72 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Figure 13.13 Binary trees

73 73 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Additional Tree Terminology Disjoint subtrees parent children siblings ancestor descendant

74 74 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Binary Search Tree Efficient data retrieval Data stored by unique key Each node has 1 data component Each node has value that is less than all values in right subtree are greater than all values stored in the left subtree –Must be true for all nodes in the binary search tree

75 75 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Searching a Binary Search Tree if (tree is empty) target is not in the tree else if (the target key is in the root) target found in root else if (target key smaller than the root’s key) search left subtree else search right subtree

76 76 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Figure 13.14 Searching for key 42

77 77 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Building a Binary Search Tree Process items in no particular order Tree created from root downward Item 1 stored in root Next item is attached to left tree if value is smaller or right tree if value is larger When inserting an item into existing tree must locate the item’s parent and then insert

78 78 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Algorithm for Insertion if (tree is empty) insert new item in tree’s root node else if (root’s key matches new item’s key) skip insertion - duplicate key else if (new key is smaller than root’s key) insert new item in left subtree else insert new item in right subtree

79 79 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Figure 13.15 Building a binary search tree

80 80 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Displaying a Binary Search Tree Recursive algorithm 1. if (tree is not empty) 2. display left subtree 3. display root item 4. display right subtree Inorder traversal Also preorder and postorder traversals

81 81 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 13.7 Binary Search Tree ADT Attributes –rootpointer to the tree root Member Functions –binaryTreea constructor –insertinserts an item –retrieveretrieves an item –searchlocates a node for a key –displaydisplays a tree

82 82 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Listing 13.8 Template class specification for tree

83 83 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Listing 13.8 Template class specification for tree (continued)

84 84 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Listing 13.8 Template class specification for tree (continued)

85 85 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Listing 13.9 Member functions binaryTree and search

86 86 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Listing 13.9 Member functions binaryTree and search (continued)

87 87 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Listing 13.10 Member functions insert

88 88 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Listing 13.10 Member functions insert (continued)

89 89 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Listing 13.11 Member functions display

90 90 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 13.8 Efficiency of a Binary Search Tree Searching for a target in a linked list is O(N) –Time is proportional to the size of the list Binary Tree more efficient –because of cutting in half process Possibly not have nodes matched evenly Best case efficiency is O(log  N)

91 91 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Values of N versus log 2 N Nlog 2 N 325 646 1287 2568 5129 102410

92 92 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 13.9 Common Programming Errors Syntax Errors –Misuse of * and -> –Misuse of new and delete Run-Time Errors –Missing braces –NULL pointer reference –Pointers as reference parameters –Heap overflow and underflow –Referencing a node on the heap


Download ppt "Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 13: Pointers and Dynamic Data Structures Problem Solving, Abstraction,"

Similar presentations


Ads by Google