Survey
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
Lecture 23: Pointers Lecture Contents: Pointers and addresses Pointers and function arguments Pointers and arrays Pointer arrays Demo programs Exercises 2 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 3 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: based on direct addressing based on indirect addressing (pointers) 4 Pointer basics Direct access to data values: int alpha=5; int beta; beta = alpha; 5 Pointer basics Indirect access to data values: int alpha=5, beta, *ptr; ptr = α beta = *ptr; 6 Pointer basics Indirect access to data values: int alpha=5, beta, *ptr; // & - address of operator ptr = α //indirection or dereferencing operator beta = *ptr; 7 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. 8 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. 9 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. 10 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); 11 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); 12 More on Pointers Pointers and Addresses 13 More on Pointers and Arrays 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]; } 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++; } 14 More on Pointers and Arrays char amessage[] = “Now is the time!”; char *pmessage; pmessage = “Now is the time!”; 15 More on Pointers and Arrays char amessage[] = “Now is the time!”; int I=0; while(amessage[I] != ‘\0’) { cout << endl << amessage[I]; I++; } 16 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++; } 17 More on Pointers Array of pointers char *pname[] = { “Illegal”, “Jan”, “Feb”, . . . “Nov”, “Dec” }; char aname[][15] ={ “Illegal”, “Jan”, “Feb”, . . . “Nov”, “Dec” }; 18 More on Pointers Multidimensional arrays and pointers int a[10][20]; int *b[10]; 19 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; } 20 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; 21 More on Pointers Address arithmetic: char a[10]; a ≡ a+0 ≡ a+I ≡ *(a+I) ≡ &a[0] &a[I] *&a[I] ≡ a[I] 22 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<q) while(q>p) Subtraction of two pointers: p=a; q=a+10; q-p is 10 23 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 cout << fact(5); Indirect function call pf = fact; cout << (*pf)(5); 24 More on Pointers Extract from Friedman/Koffman, chapter 13 25 Pointers & Dynamic Data Structures Chapter 13 Dynamic Data Structures Arrays & structs are static (compile time) Dynamic expand as program executes Linked list is example of dynamic data structure Linked list Node Node Pointer Node Pointer 27 13.1 Pointers and the “new” Operator Pointer Declarations – pointer variable of type “pointer to float” – can store the address of a float in p float *p; The new operator creates a variable of type float and puts the address of the variable in pointer p p = new float; Dynamic allocation - program execution 28 Pointers Actual address has no meaning P ? Form: Example: type *variable; float *p; 29 new Operator Actually allocates storage Form: new type; new type [n]; Example: new float; 30 Accessing Data with Pointers * - indirection operator *p = 15.5; Stores floating value 15.5 in memory location *p - the location pointed to by p p 15.5 31 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 32 Pointer Operations Pointers can only contain addresses So the following are errors: – p = 1000; – p = 15.5; Assignment of pointers if q & p are the same pointer type – q = p; Also relational operations == and != 33 13.2 Manipulating the Heap When new executes where is struct stored ? Heap – C++ storage pool available to new operator Effect of p = new node; Figure 14.1 shows Heap before and after executing new operator 34 Effect on new on the Heap 35 Returning Cells to the Heap Operation – delete p; Returns cells back to heap for re-use When finished with a pointer delete it Watch dual assignments and initialization Form: delete variable; Example: delete p; 36 13.3 Linked Lists 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 37 Children’s Beads 38 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; 39 Declaring Nodes Each var p, q and r can point to a struct of type node – word (string) – count (int) – link (pointer to a node address) Struct of type node word String count link Integer Address 40 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; 41 Figure 13.3 42 Connecting Nodes Link fields undefined until assignment p->link = q; Address of q is stored in link field pointed to by p Access elements as follows q->word or p->link->word Null stored at last link field q->link = NULL; or p->link->link = NULL; 43 Connecting Nodes 44 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; 45 Inserting a New Node in a List 46 Insertion at Head of List OldHead points to original list head oldHead = p; Point p to a new node p = new node; Connect new node to old list head p->link = oldHead; 47 Insertion at Head of List 48 Insertion at End of List Typically less efficient (no pointer) Attach new node to end of list last->link = new node; Mark end with a NULL last->link->link = NULL; 49 Insertion at End of List 50 Deleting a Node Adjust the link field to remove a node Disconnect the node pointed to by r p->link = r->link; Disconnect the node pointed to by r from its successor r->link = NULL; Return node to Heap delete r; 51 Deleting a Node 52 Traversing a List Often need to traverse a list Start at head and move down a trail of pointers Typically displaying the various nodes contents as the traversing continues Advance node pointer head = head->link; Watch use of reference parameters 53 PrintList.cpp // FILE: PrintList.cpp // DISPLAY THE LIST POINTED TO BY HEAD void printList (listNode *head) { while (head != NULL) { cout << head->word << " " << head ->count << endl; head = head->link; } } 54 Circular Lists - Two Way Option A list where the last node points back to the first node Two way list is a list that contains two pointers – pointer to next node – pointer to previous node 55 13.4 Stacks as Linked Lists Implement Stack as a dynamic structure – Earlier we used arrays (chps 12, 13) Use a linked list The first element is s.top New nodes are inserted at head of list LIFO (Last-In First-Out) StackLis.h 56 StackList.h //FILE: StackList.h #ifndef STACK_LIST_H #define STACK_LIST_H template <class stackElement> class stackList { public: // Member functions ... // CONSTRUCTOR TO CREATE AN EMPTY STACK stackList (); 57 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 58 StackList.cpp //Implementation of template class stack as a linked list #include "stackList.h" #include <cstdlib> // for NULL using namespace std; // Member functions ... template <class stackElement> stackList<stackElement>::stackList() { top = NULL; } // end stackList 59 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. 60 StackList.cpp template <class stackElement> bool stackList<stackElement>::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; 61 } // end push 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. 62 StackList.cpp template <class stackElement> bool stackList<stackElement>::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 63 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. 64 StackList.cpp template <class stackElement> bool stackList<stackElement>::peek(stackElement& x) const { bool success; // Local data if (top == NULL) success = false; else { x = top->item; success = true; } return success; } // end peek 65 StackList.cpp // Test to see if stack is empty // Pre : none // Post: Returns true if the stack is empty; // otherwise, returns false. template <class stackElement> bool stackList<stackElement>::isEmpty() const { return top == NULL; } // end isEmpty 66 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 <class stackElement> bool stackList<stackElement>::isFull() const { return false; } // end isFull 67 13.5 Queue ADT List structure where items are added to one end and removed from the opposite end FIFO (First-In First-Out) Bank service line, car wash or check-out are examples of a queue Implementing a queue as a list we added elements to the end and remove from the front Queue.h 68 Queue of Customers 69 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 queueElement> class queue { public: queue (); 70 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 71 Queue.cpp // File: queue.cpp // Implementation of template class queue #include "queue.h" #include <cstdlib> using namespace std; // for NULL // Member functions // constructor - create an empty queue template<class queueElement> queue<queueElement>::queue() { numItems = 0; front = NULL; rear = NULL; } 72 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. 73 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. 74 Queue.cpp template<class queueElement> bool queue<queueElement>::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 75 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. 76 Queue.cpp template<class queueElement> bool queue<queueElement>::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 77 Queue.cpp // Test whether queue is empty template<class queueElement> bool queue<queueElement>::isEmpty() { return (numItems == 0); } 78 Queue.cpp // Returns queue size template<class queueElement> int queue<queueElement>::getSize() { return numItems; } 79 13.6 Binary Trees List with additional pointer 2 pointers – right pointer – left pointer Binary Tree – – – – 0 - 1 or 2 successor nodes empty root left and right sub-trees 80 Binary Tree 81 Binary Search Tree Efficient data retrieval Data stored by unique key Each node has 1 data component Values stored in right sub-tree are greater than the values stored in the left sub-tree Above must be true for all nodes in the binary search tree 82 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 83 Searching for Key 42 84 Building a Binary Search Tree 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 items parent and then insert 85 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 86 Figure 13.18 Building a Tree 87 Displaying a Binary Search Tree Recursive algorithm if (tree is not empty) display left sub-tree display root display right sub-tree In-order traversal Pre and post order traversals 88 Example of traversal 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 89 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 subtree of node 30 – Display item with key 30 90 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 91 13.7 Binary Search Tree ADT Specification for a Binary Search Tree – – – – – – root binaryTree insert retrieve search display pointer to the tree root a constructor inserts an item retrieves an item locates a node for a key displays a tree 92 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 treeElement> class binTree { 93 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; 94 BinaryTree.h private: // Data type ... struct treeNode { treeElement info; treeNode* left; treeNode* right; }; 95 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 96 BinaryTree.cpp // File: binaryTree.cpp // Implementation of template class binary search tree #include "binaryTree.h" #include <iostream> using namespace std; // Member functions ... // constructor - create an empty tree template<class treeElement> binaryTree<treeElement>::binaryTree() { root = NULL; } 97 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<class treeElement> bool binaryTree<treeElement>::search (const treeElement& el) const { return search(root, el); } // search 98 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<class treeElement> bool binaryTree<treeElement>::search (treeNode* aRoot,const treeElement& el) const { if (aRoot == NULL) 99 BinaryTree.cpp return false; else if (el == aRoot->info) return true; else if (el <= aRoot->info) return search(aRoot->left, el); else return search(aRoot->right, el); } // search 100 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<class treeElement> bool binaryTree<treeElement>::insert (const treeElement& el) { return insert(root, el); } // insert 101 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<class treeElement> bool binaryTree<treeElement>::insert (treeNode*& aRoot, const treeElement& el) { 102 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; 103 BinaryTree.cpp else if (el <= aRoot->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. 104 BinaryTree.cpp template<class treeElement> void binaryTree<treeElement>::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<class treeElement> void binaryTree<treeElement>::display (treeNode* aRoot) const 105 BinaryTree.cpp { if (aRoot != NULL) { // recursive step display(aRoot->left); cout << aRoot->info << endl; display(aRoot->right); } } // display 106 BinaryTree.cpp // Insert member functions retrieve. template<class treeElement> bool binaryTree<treeElement>::retrieve (const treeElement& el) const { return retrieve(root, el); } // retrieve 107 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<class treeElement> bool binaryTree<treeElement>::retrieve (treeNode* aRoot, treeElement& el) const { return true; } 108 13.8 Efficiency of a Binary Search Tree Searching for a target in a list is O(N) Time is proportional to the size of the list Binary Tree more efficient – cutting in half process Possibly not have nodes matched evenly Efficiency is O(log N) 109 13.9 Common Programming Errors Use the * de-referencing operator Operator -> member *p refers to the entire node p->x refers to member x new operator to allocate storage delete de-allocates storage Watch out for run-time errors with loops Don’t try to access a node returned to heap 110 Exercise 25.1-25.6 Build programs based on pointers: Exchange values of two integer variables (function swap); Display a character string symbol by symbol on separate lines in forward and backward order; Define the length of a character string (own version of strlen function); Catenate two character strings (own version of strcat function); Define a function returning the name of a month as a character string; Operate as demo programs for pointers to functions. 111 Exercise 25.1-25.6 Build programs based on pointers: Display a character string symbol by symbol on separate lines in forward and backward order; 112 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++; } } 113 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++; } } 114 Exercise 25.1-25.6 Build programs based on pointers: Define the length of a character string (own version of strlen function); 115 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; } 116 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; } 117 Exercise 25.1-25.6 Build programs based on pointers: Copy a character string (own version of strcpy function); 118 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++; 119 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++; } } 120 Before lecture end Lecture: Pointers More to read: Friedman/Koffman, Chapter 13 121 Chapter 13: Pointers and Dynamic Data Structures Problem Solving, Abstraction, and Design using C++ 5e by Frank L. Friedman and Elliot B. Koffman 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 Linked list Node Node Pointer Node Pointer Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 123 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 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 124 Pointers • Actual address has no meaning for us P ? • Form: • Example: type *variable; float *p; Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 125 new Operator • Actually allocates storage • Form: new type; new type [n]; • Example: new float; Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 126 Accessing Data with Pointers • indirection operator * *p = 15.5; • Stores floating value 15.5 in memory location *p - the location pointed to by p p 15.5 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 127 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 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 128 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 != Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 129 Pointers to Structs struct electric { string current; int volts; }; electric *p, *q; • p and q are pointers to a struct of type electric Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 130 Pointers to Structs p = new electric; • Allocates storage for struct of type electric and places address into pointer p p current ? Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley volts ? 131 struct Member Access through a Pointer p ->current = “AC”; p ->volts = 115; p current AC volts 115 • Could also be referenced as (*p).current = “AC”; (*p).volts = 115; Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 132 struct Member Access through a Pointer • Form: • Example: p ->m p ->volts cout << p->current << p->volts << endl; • Output AC115 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 133 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; p current AC volts 115 q current AC volts 115 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 134 Pointers and Structs q ->volts = 220; q current AC volts 220 p->current q->current AC p->volts q->volts 115 AC 220 q = p; p q Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 135 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; Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 136 Figure 13.1 Heap before and after execution of p - new node; Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 137 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: • Example: delete variable; delete p; Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 138 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 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 139 Figure 13.2 Children’s pop beads in a chain Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 140 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; Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 141 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) Struct of type node word count link String Integer Address Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 142 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; Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 143 Figure 13.3 Nodes pointed to by p and q Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 144 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; Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 145 Figure 13.4 List with two elements Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 146 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; Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 147 Inserting a New Node in a List Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 148 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; Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 149 Figure 13.6 Insertion at the head of a list Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 150 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; Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 151 Figure 13.7 Insertion at the end of a list Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 152 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; Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 153 Figure 13.8 Deleting a list node Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 154 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 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 155 Listing 13.1 Function printList // File: printList.cpp // Display the list pointed to by head void printList (listNode *head) { while (head != NULL) { cout << head->word << " " << head->count << endl; head = head->link; } } Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 156 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 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 157 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 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 158 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&) Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 159 Listing 13.2 Using list class Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 160 Listing 13.2 Using list class (continued) Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 161 Listing 13.2 Using list class (continued) Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 162 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 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 163 A Stack of Characters * C + 2 s Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 164 The C++ stack Class • Must include stack library #include <stack> • Declare the stack stack <type> stack-name; • E.g. stack <string> nameStack; stack <char> s; Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 165 Some stack Member Functions void push(const T&) T top( ) const void pop( ) bool empty( ) const Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 166 Example x = s.top( ); s.pop( ); s.push(‘/’); // stores ‘*’ into x, stack unchanged // removes top of stack // adds ‘/’ to top of stack * / C C C + + + 2 2 2 s s s Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 167 Implementing a stack Template Class • Use linked list or vector – all insertions/deletions from same end only C s.top + C + 2 2 stack before insertion s.top * * C + stack after insertion of “*” Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 2 C + 2 168 Listing 13.4 Header file for template class stackList Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 169 Listing 13.4 Header file for template class stackList (continued) Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 170 Listing 13.5 Implementation file for template class stackList Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 171 Listing 13.5 Implementation file for template class stackList (continued) Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 172 Listing 13.5 Implementation file for template class stackList (continued) Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 173 Listing 13.5 Implementation file for template class stackList (continued) Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 174 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 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 175 Figure 13.12 Queue of customers Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 176 The C++ queue Class • Must include queue library #include <queue> • Declare the stack stack <type> queue-name; • E.g. stack <string> customers; Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 177 Member Functions of queue Class void push(const T&) T top( ) const void pop( ) bool empty( ) const int size( ) const Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 178 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 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 179 Listing 13.6 Header file for queue template class Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 180 Listing 13.6 Header file for queue template class (continued) Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 181 Listing 13.6 Header file for queue template class (continued) Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 182 Listing 13.7 Implementation file for queue template class Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 183 Listing 13.7 Implementation file for queue template class (continued) Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 184 Listing 13.7 Implementation file for queue template class (continued) Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 185 Listing 13.7 Implementation file for queue template class (continued) Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 186 Listing 13.7 Implementation file for queue template class (continued) Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 187 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 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 188 Figure 13.13 Binary trees Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 189 Additional Tree Terminology • • • • • • Disjoint subtrees parent children siblings ancestor descendant Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 190 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 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 191 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 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 192 Figure 13.14 Searching for key 42 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 193 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 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 194 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 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 195 Figure 13.15 Building a binary search tree Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 196 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 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 197 13.7 Binary Search Tree ADT • Attributes – root pointer to the tree root • Member Functions – – – – – binaryTree insert retrieve search display a constructor inserts an item retrieves an item locates a node for a key displays a tree Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 198 Listing 13.8 Template class specification for tree<treeElement> Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 199 Listing 13.8 Template class specification for tree<treeElement> (continued) Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 200 Listing 13.8 Template class specification for tree<treeElement> (continued) Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 201 Listing 13.9 Member functions binaryTree and search Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 202 Listing 13.9 Member functions binaryTree and search (continued) Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 203 Listing 13.10 Member functions insert Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 204 Listing 13.10 Member functions insert (continued) Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 205 Listing 13.11 Member functions display Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 206 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) Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 207 Values of N versus log2N N 32 64 128 256 512 1024 log2N 5 6 7 8 9 10 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 208 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 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 209 Thank You For Your Attention 210