Download presentation
Presentation is loading. Please wait.
Published byErnest Phillips Modified over 9 years ago
1
Lecture 23: Pointers
2
2 Lecture Contents: t Pointers and addresses t Pointers and function arguments t Pointers and arrays t Pointer arrays t Demo programs t Exercises
3
3 Pointer basics Pointers are variables that contain address values. Pointers are variables used to store address values. The basic concept of a pointer is: indirect access to data values
4
4 Pointer basics Given two integer variables alpha and beta. Variable alpha is defined, declared, initialized or assigned the value of 5. int alpha=5, beta; Problem: To copy the value of alpha(5) to beta Possible Solutions: t based on direct addressing t based on indirect addressing (pointers)
5
5 Pointer basics Direct access to data values: int alpha=5; int beta; beta = alpha;
6
6 Pointer basics Indirect access to data values: int alpha=5, beta, *ptr; ptr = α beta = *ptr;
7
7 Pointer basics Indirect access to data values: int alpha=5, beta, *ptr; // & - address of operator ptr = α //indirection or dereferencing operator beta = *ptr;
8
8 Declaration of pointers How to define (declare) pointers as variables? int *p1; p1 is a variable whose memory space will be used to store addresses of integer data.
9
9 Declaration of pointers How to define (declare) pointers as variables? char *p2; p2 is a variable whose memory space will be used to store addresses of character data.
10
10 Declaration of pointers How to define (declare) pointers as variables? double *p3; p3 is a variable whose memory space will be used to store addresses of double data.
11
11 How to use pointers? int alpha=5, *ptr; ptr = α // display alpha value/contents by direct/indirect addressing // C++ notation cout<< "\n" << alpha << " " << *ptr; // C notation printf(“\n%d %d”, alpha, *ptr);
12
12 How to use pointers? int alpha=5, *ptr=α // display address of alpha, I.e. contents of ptr // C++ notation cout << "\n " << &alpha << " " << ptr; // C notation printf(“\n%d %u %o %x %X %p”, ptr,ptr,ptr,ptr,ptr,ptr);
13
13 More on Pointers Pointers and Addresses
14
14 More on Pointers and Arrays t loop to traverse all array elements using direct access based on array subscripting expressions int a[10]; for (I=0;I<10;I++) { a[I]=I; cout << endl << a[I]; } t loop to traverse all array elements using indirect access based on pointers int a[10];int *pa;pa = &a[0]; for (I=0;I<10;I++) { *pa=I; cout << endl << *pa; pa++; }
15
15 More on Pointers and Arrays char amessage[] = “Now is the time!”; char *pmessage; pmessage = “Now is the time!”;
16
16 More on Pointers and Arrays char amessage[] = “Now is the time!”; int I=0; while(amessage[I] != ‘\0’) { cout << endl << amessage[I]; I++; }
17
17 More on Pointers and Arrays char *pmessage = “Now is the time!”; while(*pmessage != ‘\0’) { cout << *pmessage; pmessage++; } =================================================== char *pmessage = “Now is the time!”; char *q; q = pmessage + strlen(pmessage); while( pmessage < q ) { cout << *pmessage; pmessage++; }
18
18 More on Pointers Array of pointers char *pname[] = { “Illegal”, “Jan”, “Feb”,... “Nov”, “Dec” }; char aname[][15] ={ “Illegal”, “Jan”, “Feb”,... “Nov”, “Dec” };
19
19 More on Pointers Multidimensional arrays and pointers int a[10][20]; int *b[10];
20
20 Pointers and function arguments Problem: function to swap contents of two variables: void swap(int, int); swap(a, b); void swap(int p1, int p2) { int temp; temp=p1; p1=p2; p2=temp; }
21
21 Pointers and function arguments The solution: addresses specified as actual arguments void swap(int *, int *); swap(&a, &b); void swap(int *p1, int *p2) { int temp; temp=*p1; *p1=*p2; *p2=temp; }
22
22 More on Pointers Address arithmetic: char a[10]; a≡ a + 0≡&a[0] a + I≡&a[I] *(a+I)≡*&a[I]≡a[I]
23
23 More on Pointers Address arithmetic:int a[10], *p, *q; Assigning initial value to a pointer:p=q=a; Increment/decrement pointer: p++; p++; p--; Add a constant to pointer: q=q+8; Subtract constant from a pointer: q-=4; Comparison of two pointers:if(p p) Subtraction of two pointers: p=a; q=a+10; q-p is 10
24
24 More on Pointers Pointers to functions int fact(int n) { if(n==0) return 1; return n*fact(n-1); } int (*pf)(int);// pointer to function that has // one int param and returns int Direct function call Indirect function call cout << fact(5); pf = fact; cout << (*pf)(5);
25
25 More on Pointers Extract from Friedman/Koffman, chapter 13
26
Pointers & Dynamic Data Structures Chapter 13
27
27 Dynamic Data Structures t Arrays & structs are static (compile time) t Dynamic expand as program executes t Linked list is example of dynamic data structure Node Pointer Linked list
28
28 13.1 Pointers and the “new” Operator t Pointer Declarations –pointer variable of type “pointer to float” –can store the address of a float in p float*p; t The new operator creates a variable of type float and puts the address of the variable in pointer p p = new float; t Dynamic allocation - program execution
29
29 Pointers t Actual address has no meaning t Form:type*variable; t Example:float *p; ? P
30
30 new Operator t Actually allocates storage t Form:new type; new type [n]; t Example:new float;
31
31 Accessing Data with Pointers t * - indirection operator *p = 15.5; t Stores floating value 15.5 in memory location *p - the location pointed to by p 15.5 p
32
32 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
33
33 Pointer Operations t Pointers can only contain addresses t So the following are errors: –p = 1000; –p = 15.5; t Assignment of pointers if q & p are the same pointer type –q = p; t Also relational operations == and !=
34
34 13.2 Manipulating the Heap t When new executes where is struct stored ? t Heap –C++ storage pool available to new operator t Effect of p = new node; t Figure 14.1 shows Heap before and after executing new operator
35
35 Effect on new on the Heap
36
36 Returning Cells to the Heap t Operation –delete p; t Returns cells back to heap for re-use t When finished with a pointer delete it t Watch dual assignments and initialization t Form:deletevariable; t Example:deletep;
37
37 13.3 Linked Lists t Arrange dynamically allocated structures into a new structure called a linked list t Think of a set of children’s pop beads t Connecting beads to make a chain t You can move things around and re-connect the chain t We use pointers to create the same effect
38
38 Children’s Beads
39
39 Declaring Nodes t If a pointer is included in a struct we can connect nodes struct node { string word; int count; node *link; }; node*p, *q, *r;
40
40 Declaring Nodes t Each var p, q and r can point to a struct of type node –word(string) –count(int) –link(pointer to a node address) wordcountlink Struct of type node String Integer Address
41
41 Connecting Nodes t Allocate storage of 2 nodes p = new node; q = new node; t Assignment Statements p->word = “hat”; p->count = 2; q->word = “top”; q->count = 3;
42
42 Figure 13.3
43
43 Connecting Nodes t Link fields undefined until assignment p->link = q; t Address of q is stored in link field pointed to by p t Access elements as follows q->word or p->link->word t Null stored at last link field q->link = NULL; or p->link->link = NULL;
44
44 Connecting Nodes
45
45 Inserting a Node t Create and initialize node r = new node; r->word = “the”; r->count = 5; t Connect node pointed to by p to node pointed to by r p->link = r; t Connect node pointed to by r to node pointed to t by q r->link = q;
46
46 Inserting a New Node in a List
47
47 Insertion at Head of List t OldHead points to original list head oldHead = p; t Point p to a new node p = new node; t Connect new node to old list head p->link = oldHead;
48
48 Insertion at Head of List
49
49 Insertion at End of List t Typically less efficient (no pointer) t Attach new node to end of list last->link = new node; t Mark end with a NULL last->link->link = NULL;
50
50 Insertion at End of List
51
51 Deleting a Node t Adjust the link field to remove a node t Disconnect the node pointed to by r p->link = r->link; t Disconnect the node pointed to by r from its successor r->link = NULL; t Return node to Heap delete r;
52
52 Deleting a Node
53
53 Traversing a List t Often need to traverse a list t Start at head and move down a trail of pointers t Typically displaying the various nodes contents as the traversing continues t Advance node pointer head = head->link; t Watch use of reference parameters
54
54 PrintList.cpp // FILE: PrintList.cpp // DISPLAY THE LIST POINTED TO BY HEAD void printList (listNode *head) { while (head != NULL) { cout word count << endl; head = head->link; }
55
55 Circular Lists - Two Way Option t A list where the last node points back to the first node t Two way list is a list that contains two pointers –pointer to next node –pointer to previous node
56
56 13.4 Stacks as Linked Lists t Implement Stack as a dynamic structure –Earlier we used arrays (chps 12, 13) t Use a linked list t The first element is s.top t New nodes are inserted at head of list t LIFO (Last-In First-Out) t StackLis.h
57
57 StackList.h //FILE: StackList.h #ifndef STACK_LIST_H #define STACK_LIST_H template class stackList { public: // Member functions... // CONSTRUCTOR TO CREATE AN EMPTY STACK stackList ();
58
58 StackList.h bool push (const stackElement& x); bool pop (stackElement& x); bool peek (stackElement& x) const; bool isEmpty () const; bool isFull () const; private: struct stackNode { stackElement item; stackNode* next; }; // Data member stackNode* top; }; #endif // STACK_LIST_H
59
59 StackList.cpp //Implementation of template class stack as a linked list #include "stackList.h" #include // for NULL using namespace std; // Member functions... template stackList ::stackList() { top = NULL; } // end stackList
60
60 StackList.cpp // Push an element onto the stack // Pre: The element x is defined. // Post: If there is space on the heap, // the item is pushed onto the stack and // true is returned. Otherwise, the // stack is unchanged and false is // returned.
61
61 StackList.cpp template bool stackList ::push(const stackElement& x) { stackNode* oldTop; bool success; // Local data oldTop = top; top = new stackNode; if (top == NULL) { top = oldTop;success = false;} else { top->next = oldTop; top->item = x;success = true;} return success; } // end push
62
62 StackList.cpp // Pop an element off the stack // Pre: none // Post: If the stack is not empty, the value // at the top of the stack is removed, its // value is placed in x, and true is returned. // If stack empty, x is not defined and false returned.
63
63 StackList.cpp template bool stackList ::pop(stackElement& x) { stackNode* oldTop; bool success; if (top == NULL) success = false; else { x = top->item; oldTop = top; top = oldTop->next; delete oldTop; success = true; } return success; } // end pop
64
64 StackList.cpp // Get top element from stack without popping // Pre: none // Post: If the stack is not empty, the value // at the top is copied into x and true is // returned. If the stack is empty, x is not // defined and false is returned. In // either case, the stack is not changed.
65
65 StackList.cpp template bool stackList ::peek(stackElement& x) const { bool success; // Local data if (top == NULL) success = false; else { x = top->item; success = true; } return success; } // end peek
66
66 StackList.cpp // Test to see if stack is empty // Pre : none // Post: Returns true if the stack is empty; // otherwise, returns false. template bool stackList ::isEmpty() const { return top == NULL; } // end isEmpty
67
67 StackList.cpp // Test to see if stack is full // Pre : none // Post: Returns false. List stacks are never // full. (Does not check heap availability.) template bool stackList ::isFull() const { return false; } // end isFull
68
68 13.5 Queue ADT t List structure where items are added to one end and removed from the opposite end t FIFO (First-In First-Out) t Bank service line, car wash or check-out are examples of a queue t Implementing a queue as a list we added elements to the end and remove from the front t Queue.h
69
69 Queue of Customers
70
70 Queue.h // FILE: Queue.h // DEFINITION AND IMPLEMENTATION OF A TEMPLATE // CLASS QUEUE USING A LINKED LIST #ifndef QUEUE_H #define QUEUE_H template class queue { public: queue ();
71
71 Queue.h bool insert (const queueElement& x); bool remove (queueElement& x); bool isEmpty (); int getSize (); private: struct queueNode { queueElement item; queueNode* next; }; queueNode* front; queueNode* rear; int numItems; }; #endif // QUEUE_H
72
72 Queue.cpp // File: queue.cpp // Implementation of template class queue #include "queue.h" #include // for NULL using namespace std; // Member functions // constructor - create an empty queue template queue ::queue() { numItems = 0; front = NULL; rear = NULL; }
73
73 Queue.cpp { numItems = 0; front = NULL; rear = NULL; } // Insert an element into the queue // Pre : none // Post: If heap space is available, the // value x is inserted at the rear of the queue // and true is returned. Otherwise, the queue is // not changed and false is returned.
74
74 Queue.cpp // Insert an element into the queue // Pre : none // Post: If heap space is available, the // value x is inserted at the rear of the queue // and true is returned. Otherwise, the queue is // not changed and false is returned.
75
75 Queue.cpp template bool queue ::insert(const queueElement& x) { if (numItems == 0){ rear = new queueNode; if (rear == NULL)return false; else front = rear; } else { rear->next = new queueNode; if (rear->next == NULL) return false; else rear = rear->next; } rear->item = x; numItems++; return true; } // end insert
76
76 Queue.cpp // Remove an element from the queue // Pre : none // Post: If the queue is not empty, the value at // the front of the queue is removed, its value // is placed in x, and true is returned. If the // queue is empty, x is not defined and false // is returned.
77
77 Queue.cpp template bool queue ::remove(queueElement& x) { queueNode* oldFront; // Local data if (numItems == 0){ return false; } else { oldFront = front;x = front->item; front = front->next;oldFront->next = NULL; delete oldFront;numItems--; return true; } } // end remove
78
78 Queue.cpp // Test whether queue is empty template bool queue ::isEmpty() { return (numItems == 0); }
79
79 Queue.cpp // Returns queue size template int queue ::getSize() { return numItems; }
80
80 13.6 Binary Trees t List with additional pointer t 2 pointers –right pointer –left pointer t Binary Tree –0 - 1 or 2 successor nodes –empty –root –left and right sub-trees
81
81 Binary Tree
82
82 Binary Search Tree t Efficient data retrieval t Data stored by unique key t Each node has 1 data component t Values stored in right sub-tree are greater than the values stored in the left sub-tree t Above must be true for all nodes in the binary search tree
83
83 Searching Algorithm if (tree is empty) target is not in the tree else if (the target key is the root) target found in root else if (target key smaller than the root’s key) search left sub-tree else search right sub-tree
84
84 Searching for Key 42
85
85 Building a Binary Search Tree t Tree created from root downward t Item 1 stored in root t Next item is attached to left tree if value is smaller or right tree if value is larger t When inserting an item into existing tree must locate the items parent and then insert
86
86 Algorithm for Insertion if (tree is empty) insert new item as root else if (root key matches item) skip insertion duplicate key else if (new key is smaller than root) insert in left sub-tree else insert in right sub-tree
87
87 Figure 13.18 Building a Tree
88
88 Displaying a Binary Search Tree t Recursive algorithm if (tree is not empty) display left sub-tree display root display right sub-tree t In-order traversal t Pre and post order traversals
89
89 Example of traversal t Trace of Figure 13.18 –Display left sub-tree of node 40 –Display left sub-tree of node 20 –Display left sub-tree of node 10 –Tree is empty - return left sub-tree node is 10 –Display item with key 10 –Display right sub-tree of node 10
90
90 Example of traversal –Tree is empty - return from displaying right sub-tree node is 10 –Return from displaying left sub-tree of node 20 –Display item with key 20 –Display right sub-tree of node 20 –Display left sub-tree of node 30 –Tree is empty - return from displaying left sub- tree of node 30 –Display item with key 30
91
91 Example of traversal –Display right sub-tree of node 30 –Tree is empty - return from displaying right sub-tree of node 30 –Return from displaying right sub-tree of node 20 –Return from displaying left sub-tree of node 40 –Display item with key 40 –Display right sub-tree of node 40
92
92 13.7 Binary Search Tree ADT t Specification for a Binary Search Tree –rootpointer to the tree root –binaryTreea constructor –insertinserts an item –retrieveretrieves an item –searchlocates a node for a key –displaydisplays a tree
93
93 BinaryTree.h // FILE: BinaryTree.h // DEFINITION OF TEMPLATE CLASS BINARY SEARCH TREE #ifndef BIN_TREE_H #define BIN_TREE_H // Specification of the class template class binTree {
94
94 BinaryTree.h public: // Member functions... // CREATE AN EMPTY TREE binTree (); // INSERT AN ELEMENT INTO THE TREE bool insert (const treeElement& el ); // RETRIEVE AN ELEMENT FROM THE TREE bool retrieve (treeElement& el ) const; // SEARCH FOR AN ELEMENT IN THE TREE bool search (const treeElement& el ) const; // DISPLAY A TREE void display () const;
95
95 BinaryTree.h private: // Data type... struct treeNode { treeElement info; treeNode* left; treeNode* right; };
96
96 BinaryTree.h // Data member.... treeNode* root; // Member functions... // Searches a subtree for a key bool search (treeNode*, const treeElement&) const; // Inserts an item in a subtree bool insert (treeNode*&, const treeElement&) const; // Retrieves an item in a subtree bool retrieve (treeNode*, treeElement&) const; // Displays a subtree void display (treeNode*) const; }; #endif // BIN_TREE_H
97
97 BinaryTree.cpp // File: binaryTree.cpp // Implementation of template class binary search tree #include "binaryTree.h" #include using namespace std; // Member functions... // constructor - create an empty tree template binaryTree ::binaryTree() { root = NULL; }
98
98 BinaryTree.cpp // Searches for the item with same key as el // in a binary search tree. // Pre : el is defined. // Returns true if el's key is located, // otherwise, returns false. template bool binaryTree ::search (const treeElement& el) const { return search(root, el); } // search
99
99 BinaryTree.cpp // Searches for the item with same key as el // in the subtree pointed to by aRoot. Called // by public search. // Pre : el and aRoot are defined. // Returns true if el's key is located, // otherwise, returns false. template bool binaryTree ::search (treeNode* aRoot,const treeElement& el) const { if (aRoot == NULL)
100
100 BinaryTree.cpp return false; else if (el == aRoot->info) return true; else if (el info) return search(aRoot->left, el); else return search(aRoot->right, el); } // search
101
101 BinaryTree.cpp // Inserts item el into a binary search tree. // Pre : el is defined. // Post: Inserts el if el is not in the tree. // Returns true if the insertion is performed. // If there is a node with the same key value // as el, returns false. template bool binaryTree ::insert (const treeElement& el) { return insert(root, el); } // insert
102
102 BinaryTree.cpp // Inserts item el in the tree pointed to by // aRoot. // Called by public insert. // Pre : aRoot and el are defined. // Post: If a node with same key as el is found, // returns false. If an empty tree is reached, // inserts el as a leaf node and returns true. template bool binaryTree ::insert (treeNode*& aRoot, const treeElement& el) {
103
103 BinaryTree.cpp // Check for empty tree. if (aRoot == NULL) { // Attach new node aRoot = new treeNode; aRoot->left = NULL; aRoot->right = NULL; aRoot->info = el; return true; } else if (el == aRoot->info) return false;
104
104 BinaryTree.cpp else if (el info) return insert(aRoot->left, el); else return insert(aRoot->right, el); } // insert // Displays a binary search tree in key order. // Pre : none // Post: Each element of the tree is displayed. // Elements are displayed in key order.
105
105 BinaryTree.cpp template void binaryTree ::display() const { display(root); } // display // Displays the binary search tree pointed to // by aRoot in key order. Called by display. // Pre : aRoot is defined. // Post: displays each node in key order. template void binaryTree ::display (treeNode* aRoot) const
106
106 BinaryTree.cpp { if (aRoot != NULL) { // recursive step display(aRoot->left); cout info << endl; display(aRoot->right); } } // display
107
107 BinaryTree.cpp // Insert member functions retrieve. template bool binaryTree ::retrieve (const treeElement& el) const { return retrieve(root, el); } // retrieve
108
108 BinaryTree.cpp // Retrieves for the item with same key as el // in the subtree pointed to by aRoot. Called // by public search. // Pre : el and aRoot are defined. // Returns true if el's key is located, // otherwise, returns false. template bool binaryTree ::retrieve (treeNode* aRoot, treeElement& el) const { return true; }
109
109 13.8 Efficiency of a Binary Search Tree t Searching for a target in a list is O(N) t Time is proportional to the size of the list t Binary Tree more efficient –cutting in half process t Possibly not have nodes matched evenly t Efficiency is O(log N)
110
110 13.9 Common Programming Errors t Use the * de-referencing operator t Operator -> member t *p refers to the entire node t p->x refers to member x t new operator to allocate storage t delete de-allocates storage t Watch out for run-time errors with loops t Don’t try to access a node returned to heap
111
111 Exercise 25.1-25.6 Build programs based on pointers: t Exchange values of two integer variables (function swap); t Display a character string symbol by symbol on separate lines in forward and backward order; t Define the length of a character string (own version of strlen function); t Catenate two character strings (own version of strcat function); t Define a function returning the name of a month as a character string; t Operate as demo programs for pointers to functions.
112
112 Exercise 25.1-25.6 Build programs based on pointers: t Display a character string symbol by symbol on separate lines in forward and backward order;
113
113 Exercise 23.1 char str[] = “AUBG Blagoevgrad”; void main() { int I=0; cout << endl << str << endl; while (str[I] != ‘\0’) { cout << endl << str[I]; I++; }
114
114 Exercise 23.1 char str[] = “AUBG Blagoevgrad”; void main() { char *p = str; cout << endl << str << endl << p << endl; while ( *p != ‘\0’) { cout << endl << *p; p++; }
115
115 Exercise 25.1-25.6 Build programs based on pointers: t Define the length of a character string (own version of strlen function);
116
116 Exercise 23.1 char str[] = “AUBG Blagoevgrad”; int strlenm(char m[]); void main() { cout << endl << strlenm(str) << endl; } int strlenm(char m[]) { int I=0, len; while (m[I] != 0x00) I++; len = I; return len; }
117
117 Exercise 23.1 char str[] = “AUBG Blagoevgrad”; int strlenm(char *pm); void main() { char *p = str; cout << endl << strlenm(str) << “ “ << strlenm(p) << endl; } int strlenm(char *pm) { int len = 0; while (*pm != 0x00) { Ien++; pm++; ) return len; }
118
118 Exercise 25.1-25.6 Build programs based on pointers: t Copy a character string (own version of strcpy function);
119
119 Exercise 23.1 char str[] = “AUBG Blagoevgrad”; void copym(char dst[], char src[]); void main() { char newstr[20]; copym(newstr, str); cout << endl << newstr << endl; } void copym(char dst[], char src[]) { int I=0; while(( dst[I] = src[I] ) != ‘\0’)I++; }
120
120 Exercise 23.1 char str[] = “AUBG Blagoevgrad”; void copym(char *dst, char *src); void main() { char *newstr;newstr = new char[20]; copym(newstr, str); cout << endl << newstr << endl; } void copym(char *dst, char *src) { while(( *dst = *src ) != ‘\0’) { dst++; src++; } }
121
121 Before lecture end Lecture: Pointers More to read: Friedman/Koffman, Chapter 13
122
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 13: Pointers and Dynamic Data Structures Problem Solving, Abstraction, and Design using C++ 5e by Frank L. Friedman and Elliot B. Koffman
123
123 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
124
124 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
125
125 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
126
126 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley new Operator Actually allocates storage Form:new type; new type [n]; Example:new float;
127
127 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
128
128 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
129
129 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 !=
130
130 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
131
131 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 ??
132
132 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
133
133 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
134
134 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
135
135 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
136
136 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;
137
137 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Figure 13.1 Heap before and after execution of p - new node;
138
138 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;
139
139 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
140
140 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Figure 13.2 Children’s pop beads in a chain
141
141 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;
142
142 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
143
143 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;
144
144 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Figure 13.3 Nodes pointed to by p and q
145
145 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;
146
146 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Figure 13.4 List with two elements
147
147 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;
148
148 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Inserting a New Node in a List
149
149 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;
150
150 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Figure 13.6 Insertion at the head of a list
151
151 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;
152
152 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Figure 13.7 Insertion at the end of a list
153
153 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;
154
154 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Figure 13.8 Deleting a list node
155
155 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
156
156 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; }
157
157 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
158
158 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
159
159 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&)
160
160 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Listing 13.2 Using list class
161
161 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Listing 13.2 Using list class (continued)
162
162 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Listing 13.2 Using list class (continued)
163
163 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
164
164 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley A Stack of Characters *C+2*C+2 s
165
165 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;
166
166 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
167
167 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
168
168 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
169
169 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Listing 13.4 Header file for template class stackList
170
170 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Listing 13.4 Header file for template class stackList (continued)
171
171 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Listing 13.5 Implementation file for template class stackList
172
172 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Listing 13.5 Implementation file for template class stackList (continued)
173
173 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Listing 13.5 Implementation file for template class stackList (continued)
174
174 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Listing 13.5 Implementation file for template class stackList (continued)
175
175 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
176
176 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Figure 13.12 Queue of customers
177
177 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;
178
178 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
179
179 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
180
180 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Listing 13.6 Header file for queue template class
181
181 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Listing 13.6 Header file for queue template class (continued)
182
182 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Listing 13.6 Header file for queue template class (continued)
183
183 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Listing 13.7 Implementation file for queue template class
184
184 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Listing 13.7 Implementation file for queue template class (continued)
185
185 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Listing 13.7 Implementation file for queue template class (continued)
186
186 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Listing 13.7 Implementation file for queue template class (continued)
187
187 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Listing 13.7 Implementation file for queue template class (continued)
188
188 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
189
189 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Figure 13.13 Binary trees
190
190 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Additional Tree Terminology Disjoint subtrees parent children siblings ancestor descendant
191
191 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
192
192 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
193
193 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Figure 13.14 Searching for key 42
194
194 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
195
195 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
196
196 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Figure 13.15 Building a binary search tree
197
197 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
198
198 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
199
199 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Listing 13.8 Template class specification for tree
200
200 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Listing 13.8 Template class specification for tree (continued)
201
201 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Listing 13.8 Template class specification for tree (continued)
202
202 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Listing 13.9 Member functions binaryTree and search
203
203 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Listing 13.9 Member functions binaryTree and search (continued)
204
204 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Listing 13.10 Member functions insert
205
205 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Listing 13.10 Member functions insert (continued)
206
206 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Listing 13.11 Member functions display
207
207 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)
208
208 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
209
209 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
210
210 Thank You For Your Attention
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.