210
Lecture 23: Pointers

Lecture 23: Pointers. 2 Lecture Contents: t Pointers and addresses t Pointers and function arguments t Pointers and arrays t Pointer arrays t Demo programs

Embed Size (px)

Citation preview

Page 1: Lecture 23: Pointers. 2 Lecture Contents: t Pointers and addresses t Pointers and function arguments t Pointers and arrays t Pointer arrays t Demo programs

Lecture 23:Pointers

Page 2: Lecture 23: Pointers. 2 Lecture Contents: t Pointers and addresses t Pointers and function arguments t Pointers and arrays t Pointer arrays t Demo programs

2

Lecture Contents:

Pointers and addresses Pointers and function arguments Pointers and arrays Pointer arrays Demo programs Exercises

Page 3: Lecture 23: Pointers. 2 Lecture Contents: t Pointers and addresses t Pointers and function arguments t Pointers and arrays t Pointer arrays t Demo programs

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

Page 4: Lecture 23: Pointers. 2 Lecture Contents: t Pointers and addresses t Pointers and function arguments t Pointers and arrays t Pointer arrays t Demo programs

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: based on direct addressing based on indirect addressing

(pointers)

Page 5: Lecture 23: Pointers. 2 Lecture Contents: t Pointers and addresses t Pointers and function arguments t Pointers and arrays t Pointer arrays t Demo programs

5

Pointer basics

Direct access to data values:

int alpha=5; int beta;

beta = alpha;

Page 6: Lecture 23: Pointers. 2 Lecture Contents: t Pointers and addresses t Pointers and function arguments t Pointers and arrays t Pointer arrays t Demo programs

6

Pointer basics

Indirect access to data values:

int alpha=5, beta, *ptr;

ptr = α

beta = *ptr;

Page 7: Lecture 23: Pointers. 2 Lecture Contents: t Pointers and addresses t Pointers and function arguments t Pointers and arrays t Pointer arrays t Demo programs

7

Pointer basics

Indirect access to data values:int alpha=5, beta, *ptr;

// & - address of operatorptr = α

//indirection or dereferencing operator

beta = *ptr;

Page 8: Lecture 23: Pointers. 2 Lecture Contents: t Pointers and addresses t Pointers and function arguments t Pointers and arrays t Pointer arrays t Demo programs

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.

Page 9: Lecture 23: Pointers. 2 Lecture Contents: t Pointers and addresses t Pointers and function arguments t Pointers and arrays t Pointer arrays t Demo programs

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.

Page 10: Lecture 23: Pointers. 2 Lecture Contents: t Pointers and addresses t Pointers and function arguments t Pointers and arrays t Pointer arrays t Demo programs

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.

Page 11: Lecture 23: Pointers. 2 Lecture Contents: t Pointers and addresses t Pointers and function arguments t Pointers and arrays t Pointer arrays t Demo programs

11

How to use pointers?

int alpha=5, *ptr;ptr = α

// display alpha value/contents by direct/indirect addressing// C++ notationcout<< "\n" << alpha << " " << *ptr;

// C notationprintf(“\n%d %d”, alpha, *ptr);

Page 12: Lecture 23: Pointers. 2 Lecture Contents: t Pointers and addresses t Pointers and function arguments t Pointers and arrays t Pointer arrays t Demo programs

12

How to use pointers?

int alpha=5, *ptr=&alpha;

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

Page 13: Lecture 23: Pointers. 2 Lecture Contents: t Pointers and addresses t Pointers and function arguments t Pointers and arrays t Pointer arrays t Demo programs

13

More on Pointers

Pointers and Addresses 

Page 14: Lecture 23: Pointers. 2 Lecture Contents: t Pointers and addresses t Pointers and function arguments t Pointers and arrays t Pointer arrays t Demo programs

14

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

Page 15: Lecture 23: Pointers. 2 Lecture Contents: t Pointers and addresses t Pointers and function arguments t Pointers and arrays t Pointer arrays t Demo programs

15

More on Pointers and Arrays

char amessage[] = “Now is the time!”;

char *pmessage;

pmessage = “Now is the time!”;

Page 16: Lecture 23: Pointers. 2 Lecture Contents: t Pointers and addresses t Pointers and function arguments t Pointers and arrays t Pointer arrays t Demo programs

16

More on Pointers and Arrays

char amessage[] = “Now is the time!”;

int I=0;

while(amessage[I] != ‘\0’)

{

cout << endl << amessage[I];

I++;

}

Page 17: Lecture 23: Pointers. 2 Lecture Contents: t Pointers and addresses t Pointers and function arguments t Pointers and arrays t Pointer arrays t Demo programs

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

Page 18: Lecture 23: Pointers. 2 Lecture Contents: t Pointers and addresses t Pointers and function arguments t Pointers and arrays t Pointer arrays t Demo programs

18

More on Pointers

Array of pointers

char *pname[] = { “Illegal”, “Jan”, “Feb”, . . .

“Nov”, “Dec” };

char aname[][15] ={ “Illegal”, “Jan”, “Feb”,

. . . “Nov”, “Dec” };

Page 19: Lecture 23: Pointers. 2 Lecture Contents: t Pointers and addresses t Pointers and function arguments t Pointers and arrays t Pointer arrays t Demo programs

19

More on Pointers

Multidimensional arrays and pointers

int a[10][20];

int *b[10];

Page 20: Lecture 23: Pointers. 2 Lecture Contents: t Pointers and addresses t Pointers and function arguments t Pointers and arrays t Pointer arrays t Demo programs

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

Page 21: Lecture 23: Pointers. 2 Lecture Contents: t Pointers and addresses t Pointers and function arguments t Pointers and arrays t Pointer arrays t Demo programs

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

Page 22: Lecture 23: Pointers. 2 Lecture Contents: t Pointers and addresses t Pointers and function arguments t Pointers and arrays t Pointer arrays t Demo programs

22

More on Pointers

Address arithmetic:

char a[10];

a ≡ a + 0 ≡ &a[0]

a + I ≡ &a[I]

*(a+I) ≡ *&a[I] ≡ a[I]

Page 23: Lecture 23: Pointers. 2 Lecture Contents: t Pointers and addresses t Pointers and function arguments t Pointers and arrays t Pointer arrays t Demo programs

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<q) while(q>p)

Subtraction of two pointers: p=a; q=a+10; q-p is 10

Page 24: Lecture 23: Pointers. 2 Lecture Contents: t Pointers and addresses t Pointers and function arguments t Pointers and arrays t Pointer arrays t Demo programs

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 callcout << fact(5); pf = fact;

cout << (*pf)(5);

Page 25: Lecture 23: Pointers. 2 Lecture Contents: t Pointers and addresses t Pointers and function arguments t Pointers and arrays t Pointer arrays t Demo programs

25

More on Pointers

Extract from Friedman/Koffman, chapter 13

Page 26: Lecture 23: Pointers. 2 Lecture Contents: t Pointers and addresses t Pointers and function arguments t Pointers and arrays t Pointer arrays t Demo programs

Pointers & Dynamic Data Structures

Chapter 13

Page 27: Lecture 23: Pointers. 2 Lecture Contents: t Pointers and addresses t Pointers and function arguments t Pointers and arrays t Pointer arrays t Demo programs

27

Dynamic Data Structures

Arrays & structs are static (compile time) Dynamic expand as program executes Linked list is example of dynamic data

structure

Node Node Node

PointerPointer

Linked list

Page 28: Lecture 23: Pointers. 2 Lecture Contents: t Pointers and addresses t Pointers and function arguments t Pointers and arrays t Pointer arrays t Demo programs

28

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 pp = new float;

Dynamic allocation - program execution

Page 29: Lecture 23: Pointers. 2 Lecture Contents: t Pointers and addresses t Pointers and function arguments t Pointers and arrays t Pointer arrays t Demo programs

29

Pointers

Actual address has no meaning

Form: type *variable; Example: float *p;

?

P

Page 30: Lecture 23: Pointers. 2 Lecture Contents: t Pointers and addresses t Pointers and function arguments t Pointers and arrays t Pointer arrays t Demo programs

30

new Operator

Actually allocates storage

Form: new type;

new type [n];

Example: new float;

Page 31: Lecture 23: Pointers. 2 Lecture Contents: t Pointers and addresses t Pointers and function arguments t Pointers and arrays t Pointer arrays t Demo programs

31

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

Page 32: Lecture 23: Pointers. 2 Lecture Contents: t Pointers and addresses t Pointers and function arguments t Pointers and arrays t Pointer arrays t Demo programs

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;

OutputThe contents of memory cell pointed to by p is 15.5

Page 33: Lecture 23: Pointers. 2 Lecture Contents: t Pointers and addresses t Pointers and function arguments t Pointers and arrays t Pointer arrays t Demo programs

33

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

Page 34: Lecture 23: Pointers. 2 Lecture Contents: t Pointers and addresses t Pointers and function arguments t Pointers and arrays t Pointer arrays t Demo programs

34

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

Page 35: Lecture 23: Pointers. 2 Lecture Contents: t Pointers and addresses t Pointers and function arguments t Pointers and arrays t Pointer arrays t Demo programs

35

Effect on new on the Heap

Page 36: Lecture 23: Pointers. 2 Lecture Contents: t Pointers and addresses t Pointers and function arguments t Pointers and arrays t Pointer arrays t Demo programs

36

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;

Page 37: Lecture 23: Pointers. 2 Lecture Contents: t Pointers and addresses t Pointers and function arguments t Pointers and arrays t Pointer arrays t Demo programs

37

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

Page 38: Lecture 23: Pointers. 2 Lecture Contents: t Pointers and addresses t Pointers and function arguments t Pointers and arrays t Pointer arrays t Demo programs

38

Children’s Beads

Page 39: Lecture 23: Pointers. 2 Lecture Contents: t Pointers and addresses t Pointers and function arguments t Pointers and arrays t Pointer arrays t Demo programs

39

Declaring Nodes

If a pointer is included in a struct we can connect nodesstruct node

{

string word;

int count;

node *link;

};

node *p, *q, *r;

Page 40: Lecture 23: Pointers. 2 Lecture Contents: t Pointers and addresses t Pointers and function arguments t Pointers and arrays t Pointer arrays t Demo programs

40

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)

word count link

Struct of type node

String Integer Address

Page 41: Lecture 23: Pointers. 2 Lecture Contents: t Pointers and addresses t Pointers and function arguments t Pointers and arrays t Pointer arrays t Demo programs

41

Connecting Nodes

Allocate storage of 2 nodesp = new node;q = new node;

Assignment Statementsp->word = “hat”;p->count = 2;q->word = “top”;q->count = 3;

Page 42: Lecture 23: Pointers. 2 Lecture Contents: t Pointers and addresses t Pointers and function arguments t Pointers and arrays t Pointer arrays t Demo programs

42

Figure 13.3

Page 43: Lecture 23: Pointers. 2 Lecture Contents: t Pointers and addresses t Pointers and function arguments t Pointers and arrays t Pointer arrays t Demo programs

43

Connecting Nodes

Link fields undefined until assignmentp->link = q;

Address of q is stored in link field pointed to by p

Access elements as followsq->word or p->link->word

Null stored at last link fieldq->link = NULL; or p->link->link = NULL;

Page 44: Lecture 23: Pointers. 2 Lecture Contents: t Pointers and addresses t Pointers and function arguments t Pointers and arrays t Pointer arrays t Demo programs

44

Connecting Nodes

Page 45: Lecture 23: Pointers. 2 Lecture Contents: t Pointers and addresses t Pointers and function arguments t Pointers and arrays t Pointer arrays t Demo programs

45

Inserting a Node

Create and initialize noder = new node;r->word = “the”;r->count = 5;

Connect node pointed to by p to node pointed to by rp->link = r;

Connect node pointed to by r to node pointed to by q

r->link = q;

Page 46: Lecture 23: Pointers. 2 Lecture Contents: t Pointers and addresses t Pointers and function arguments t Pointers and arrays t Pointer arrays t Demo programs

46

Inserting a New Node in a List

Page 47: Lecture 23: Pointers. 2 Lecture Contents: t Pointers and addresses t Pointers and function arguments t Pointers and arrays t Pointer arrays t Demo programs

47

Insertion at Head of List

OldHead points to original list headoldHead = p;

Point p to a new nodep = new node;

Connect new node to old list headp->link = oldHead;

Page 48: Lecture 23: Pointers. 2 Lecture Contents: t Pointers and addresses t Pointers and function arguments t Pointers and arrays t Pointer arrays t Demo programs

48

Insertion at Head of List

Page 49: Lecture 23: Pointers. 2 Lecture Contents: t Pointers and addresses t Pointers and function arguments t Pointers and arrays t Pointer arrays t Demo programs

49

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;

Page 50: Lecture 23: Pointers. 2 Lecture Contents: t Pointers and addresses t Pointers and function arguments t Pointers and arrays t Pointer arrays t Demo programs

50

Insertion at End of List

Page 51: Lecture 23: Pointers. 2 Lecture Contents: t Pointers and addresses t Pointers and function arguments t Pointers and arrays t Pointer arrays t Demo programs

51

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

successorr->link = NULL;

Return node to Heapdelete r;

Page 52: Lecture 23: Pointers. 2 Lecture Contents: t Pointers and addresses t Pointers and function arguments t Pointers and arrays t Pointer arrays t Demo programs

52

Deleting a Node

Page 53: Lecture 23: Pointers. 2 Lecture Contents: t Pointers and addresses t Pointers and function arguments t Pointers and arrays t Pointer arrays t Demo programs

53

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

Page 54: Lecture 23: Pointers. 2 Lecture Contents: t Pointers and addresses t Pointers and function arguments t Pointers and arrays t Pointer arrays t Demo programs

54

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;

}

}

Page 55: Lecture 23: Pointers. 2 Lecture Contents: t Pointers and addresses t Pointers and function arguments t Pointers and arrays t Pointer arrays t Demo programs

55

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

Page 56: Lecture 23: Pointers. 2 Lecture Contents: t Pointers and addresses t Pointers and function arguments t Pointers and arrays t Pointer arrays t Demo programs

56

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

Page 57: Lecture 23: Pointers. 2 Lecture Contents: t Pointers and addresses t Pointers and function arguments t Pointers and arrays t Pointer arrays t Demo programs

57

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

Page 58: Lecture 23: Pointers. 2 Lecture Contents: t Pointers and addresses t Pointers and function arguments t Pointers and arrays t Pointer arrays t Demo programs

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

Page 59: Lecture 23: Pointers. 2 Lecture Contents: t Pointers and addresses t Pointers and function arguments t Pointers and arrays t Pointer arrays t Demo programs

59

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

Page 60: Lecture 23: Pointers. 2 Lecture Contents: t Pointers and addresses t Pointers and function arguments t Pointers and arrays t Pointer arrays t Demo programs

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.

Page 61: Lecture 23: Pointers. 2 Lecture Contents: t Pointers and addresses t Pointers and function arguments t Pointers and arrays t Pointer arrays t Demo programs

61

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;} // end push

Page 62: Lecture 23: Pointers. 2 Lecture Contents: t Pointers and addresses t Pointers and function arguments t Pointers and arrays t Pointer arrays t Demo programs

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.

Page 63: Lecture 23: Pointers. 2 Lecture Contents: t Pointers and addresses t Pointers and function arguments t Pointers and arrays t Pointer arrays t Demo programs

63

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

Page 64: Lecture 23: Pointers. 2 Lecture Contents: t Pointers and addresses t Pointers and function arguments t Pointers and arrays t Pointer arrays t Demo programs

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.

Page 65: Lecture 23: Pointers. 2 Lecture Contents: t Pointers and addresses t Pointers and function arguments t Pointers and arrays t Pointer arrays t Demo programs

65

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

Page 66: Lecture 23: Pointers. 2 Lecture Contents: t Pointers and addresses t Pointers and function arguments t Pointers and arrays t Pointer arrays t Demo programs

66

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

Page 67: Lecture 23: Pointers. 2 Lecture Contents: t Pointers and addresses t Pointers and function arguments t Pointers and arrays t Pointer arrays t Demo programs

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

bool stackList<stackElement>::isFull() const

{

return false;

} // end isFull

Page 68: Lecture 23: Pointers. 2 Lecture Contents: t Pointers and addresses t Pointers and function arguments t Pointers and arrays t Pointer arrays t Demo programs

68

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

Page 69: Lecture 23: Pointers. 2 Lecture Contents: t Pointers and addresses t Pointers and function arguments t Pointers and arrays t Pointer arrays t Demo programs

69

Queue of Customers

Page 70: Lecture 23: Pointers. 2 Lecture Contents: t Pointers and addresses t Pointers and function arguments t Pointers and arrays t Pointer arrays t Demo programs

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 queueElement>class queue{ public: queue ();

Page 71: Lecture 23: Pointers. 2 Lecture Contents: t Pointers and addresses t Pointers and function arguments t Pointers and arrays t Pointer arrays t Demo programs

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

Page 72: Lecture 23: Pointers. 2 Lecture Contents: t Pointers and addresses t Pointers and function arguments t Pointers and arrays t Pointer arrays t Demo programs

72

Queue.cpp

// File: queue.cpp// Implementation of template class queue

#include "queue.h"#include <cstdlib> // for NULLusing namespace std;

// Member functions // constructor - create an empty queuetemplate<class queueElement>queue<queueElement>::queue(){ numItems = 0; front = NULL; rear = NULL;}

Page 73: Lecture 23: Pointers. 2 Lecture Contents: t Pointers and addresses t Pointers and function arguments t Pointers and arrays t Pointer arrays t Demo programs

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.

Page 74: Lecture 23: Pointers. 2 Lecture Contents: t Pointers and addresses t Pointers and function arguments t Pointers and arrays t Pointer arrays t Demo programs

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.

Page 75: Lecture 23: Pointers. 2 Lecture Contents: t Pointers and addresses t Pointers and function arguments t Pointers and arrays t Pointer arrays t Demo programs

75

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

Page 76: Lecture 23: Pointers. 2 Lecture Contents: t Pointers and addresses t Pointers and function arguments t Pointers and arrays t Pointer arrays t Demo programs

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.

Page 77: Lecture 23: Pointers. 2 Lecture Contents: t Pointers and addresses t Pointers and function arguments t Pointers and arrays t Pointer arrays t Demo programs

77

Queue.cpp

template<class queueElement>bool queue<queueElement>::remove(queueElement& x){

queueNode* oldFront; // Local dataif (numItems == 0) {

return false; } else {

oldFront = front; x = front->item; front = front->next; oldFront->next = NULL; delete oldFront; numItems--; return true;

}} // end remove

Page 78: Lecture 23: Pointers. 2 Lecture Contents: t Pointers and addresses t Pointers and function arguments t Pointers and arrays t Pointer arrays t Demo programs

78

Queue.cpp

// Test whether queue is empty

template<class queueElement>

bool queue<queueElement>::isEmpty()

{

return (numItems == 0);

}

Page 79: Lecture 23: Pointers. 2 Lecture Contents: t Pointers and addresses t Pointers and function arguments t Pointers and arrays t Pointer arrays t Demo programs

79

Queue.cpp

// Returns queue size

template<class queueElement>

int queue<queueElement>::getSize()

{

return numItems;

}

Page 80: Lecture 23: Pointers. 2 Lecture Contents: t Pointers and addresses t Pointers and function arguments t Pointers and arrays t Pointer arrays t Demo programs

80

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

Page 81: Lecture 23: Pointers. 2 Lecture Contents: t Pointers and addresses t Pointers and function arguments t Pointers and arrays t Pointer arrays t Demo programs

81

Binary Tree

Page 82: Lecture 23: Pointers. 2 Lecture Contents: t Pointers and addresses t Pointers and function arguments t Pointers and arrays t Pointer arrays t Demo programs

82

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

Page 83: Lecture 23: Pointers. 2 Lecture Contents: t Pointers and addresses t Pointers and function arguments t Pointers and arrays t Pointer arrays t Demo programs

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

Page 84: Lecture 23: Pointers. 2 Lecture Contents: t Pointers and addresses t Pointers and function arguments t Pointers and arrays t Pointer arrays t Demo programs

84

Searching for Key 42

Page 85: Lecture 23: Pointers. 2 Lecture Contents: t Pointers and addresses t Pointers and function arguments t Pointers and arrays t Pointer arrays t Demo programs

85

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

Page 86: Lecture 23: Pointers. 2 Lecture Contents: t Pointers and addresses t Pointers and function arguments t Pointers and arrays t Pointer arrays t Demo programs

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

Page 87: Lecture 23: Pointers. 2 Lecture Contents: t Pointers and addresses t Pointers and function arguments t Pointers and arrays t Pointer arrays t Demo programs

87

Figure 13.18 Building a Tree

Page 88: Lecture 23: Pointers. 2 Lecture Contents: t Pointers and addresses t Pointers and function arguments t Pointers and arrays t Pointer arrays t Demo programs

88

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

Page 89: Lecture 23: Pointers. 2 Lecture Contents: t Pointers and addresses t Pointers and function arguments t Pointers and arrays t Pointer arrays t Demo programs

89

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

Page 90: Lecture 23: Pointers. 2 Lecture Contents: t Pointers and addresses t Pointers and function arguments t Pointers and arrays t Pointer arrays t Demo programs

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

Page 91: Lecture 23: Pointers. 2 Lecture Contents: t Pointers and addresses t Pointers and function arguments t Pointers and arrays t Pointer arrays t Demo programs

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

Page 92: Lecture 23: Pointers. 2 Lecture Contents: t Pointers and addresses t Pointers and function arguments t Pointers and arrays t Pointer arrays t Demo programs

92

13.7 Binary Search Tree ADT

Specification for a Binary Search Tree– root pointer to the tree root– binaryTree a constructor– insert inserts an item– retrieve retrieves an item– search locates a node for a key– display displays a tree

Page 93: Lecture 23: Pointers. 2 Lecture Contents: t Pointers and addresses t Pointers and function arguments t Pointers and arrays t Pointer arrays t Demo programs

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

class binTree

{

Page 94: Lecture 23: Pointers. 2 Lecture Contents: t Pointers and addresses t Pointers and function arguments t Pointers and arrays t Pointer arrays t Demo programs

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;

Page 95: Lecture 23: Pointers. 2 Lecture Contents: t Pointers and addresses t Pointers and function arguments t Pointers and arrays t Pointer arrays t Demo programs

95

BinaryTree.h

private: // Data type ... struct treeNode { treeElement info; treeNode* left; treeNode* right;

};

Page 96: Lecture 23: Pointers. 2 Lecture Contents: t Pointers and addresses t Pointers and function arguments t Pointers and arrays t Pointer arrays t Demo programs

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

Page 97: Lecture 23: Pointers. 2 Lecture Contents: t Pointers and addresses t Pointers and function arguments t Pointers and arrays t Pointer arrays t Demo programs

97

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 treetemplate<class treeElement>binaryTree<treeElement>::binaryTree(){ root = NULL;}

Page 98: Lecture 23: Pointers. 2 Lecture Contents: t Pointers and addresses t Pointers and function arguments t Pointers and arrays t Pointer arrays t Demo programs

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<class treeElement>bool binaryTree<treeElement>::search (const treeElement& el) const { return search(root, el); } // search

Page 99: Lecture 23: Pointers. 2 Lecture Contents: t Pointers and addresses t Pointers and function arguments t Pointers and arrays t Pointer arrays t Demo programs

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<class treeElement>bool binaryTree<treeElement>::search (treeNode* aRoot,const treeElement& el)

const{ if (aRoot == NULL)

Page 100: Lecture 23: Pointers. 2 Lecture Contents: t Pointers and addresses t Pointers and function arguments t Pointers and arrays t Pointer arrays t Demo programs

100

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

Page 101: Lecture 23: Pointers. 2 Lecture Contents: t Pointers and addresses t Pointers and function arguments t Pointers and arrays t Pointer arrays t Demo programs

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<class treeElement>bool binaryTree<treeElement>::insert (const treeElement& el){ return insert(root, el);} // insert

Page 102: Lecture 23: Pointers. 2 Lecture Contents: t Pointers and addresses t Pointers and function arguments t Pointers and arrays t Pointer arrays t Demo programs

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<class treeElement>bool binaryTree<treeElement>::insert (treeNode*& aRoot, const treeElement& el){

Page 103: Lecture 23: Pointers. 2 Lecture Contents: t Pointers and addresses t Pointers and function arguments t Pointers and arrays t Pointer arrays t Demo programs

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;

Page 104: Lecture 23: Pointers. 2 Lecture Contents: t Pointers and addresses t Pointers and function arguments t Pointers and arrays t Pointer arrays t Demo programs

104

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.

Page 105: Lecture 23: Pointers. 2 Lecture Contents: t Pointers and addresses t Pointers and function arguments t Pointers and arrays t Pointer arrays t Demo programs

105

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

Page 106: Lecture 23: Pointers. 2 Lecture Contents: t Pointers and addresses t Pointers and function arguments t Pointers and arrays t Pointer arrays t Demo programs

106

BinaryTree.cpp

{

if (aRoot != NULL)

{ // recursive step

display(aRoot->left);

cout << aRoot->info << endl;

display(aRoot->right);

}

} // display

Page 107: Lecture 23: Pointers. 2 Lecture Contents: t Pointers and addresses t Pointers and function arguments t Pointers and arrays t Pointer arrays t Demo programs

107

BinaryTree.cpp

// Insert member functions retrieve.

template<class treeElement>

bool binaryTree<treeElement>::retrieve

(const treeElement& el) const

{

return retrieve(root, el);

} // retrieve

Page 108: Lecture 23: Pointers. 2 Lecture Contents: t Pointers and addresses t Pointers and function arguments t Pointers and arrays t Pointer arrays t Demo programs

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<class treeElement>bool binaryTree<treeElement>::retrieve (treeNode* aRoot, treeElement& el) const{ return true;}

Page 109: Lecture 23: Pointers. 2 Lecture Contents: t Pointers and addresses t Pointers and function arguments t Pointers and arrays t Pointer arrays t Demo programs

109

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)

Page 110: Lecture 23: Pointers. 2 Lecture Contents: t Pointers and addresses t Pointers and function arguments t Pointers and arrays t Pointer arrays t Demo programs

110

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

Page 111: Lecture 23: Pointers. 2 Lecture Contents: t Pointers and addresses t Pointers and function arguments t Pointers and arrays t Pointer arrays t Demo programs

111

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.

Page 112: Lecture 23: Pointers. 2 Lecture Contents: t Pointers and addresses t Pointers and function arguments t Pointers and arrays t Pointer arrays t Demo programs

112

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;

Page 113: Lecture 23: Pointers. 2 Lecture Contents: t Pointers and addresses t Pointers and function arguments t Pointers and arrays t Pointer arrays t Demo programs

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

}}

Page 114: Lecture 23: Pointers. 2 Lecture Contents: t Pointers and addresses t Pointers and function arguments t Pointers and arrays t Pointer arrays t Demo programs

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

}}

Page 115: Lecture 23: Pointers. 2 Lecture Contents: t Pointers and addresses t Pointers and function arguments t Pointers and arrays t Pointer arrays t Demo programs

115

Exercise 25.1-25.6

Build programs based on pointers:

Define the length of a character string (own version of strlen function);

Page 116: Lecture 23: Pointers. 2 Lecture Contents: t Pointers and addresses t Pointers and function arguments t Pointers and arrays t Pointer arrays t Demo programs

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;

}

Page 117: Lecture 23: Pointers. 2 Lecture Contents: t Pointers and addresses t Pointers and function arguments t Pointers and arrays t Pointer arrays t Demo programs

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;

}

Page 118: Lecture 23: Pointers. 2 Lecture Contents: t Pointers and addresses t Pointers and function arguments t Pointers and arrays t Pointer arrays t Demo programs

118

Exercise 25.1-25.6

Build programs based on pointers:

Copy a character string (own version of strcpy function);

Page 119: Lecture 23: Pointers. 2 Lecture Contents: t Pointers and addresses t Pointers and function arguments t Pointers and arrays t Pointer arrays t Demo programs

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

}

Page 120: Lecture 23: Pointers. 2 Lecture Contents: t Pointers and addresses t Pointers and function arguments t Pointers and arrays t Pointer arrays t Demo programs

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

}

Page 121: Lecture 23: Pointers. 2 Lecture Contents: t Pointers and addresses t Pointers and function arguments t Pointers and arrays t Pointer arrays t Demo programs

121

Before lecture end

Lecture:Pointers

More to read:

Friedman/Koffman, Chapter 13

Page 122: Lecture 23: Pointers. 2 Lecture Contents: t Pointers and addresses t Pointers and function arguments t Pointers and arrays t Pointer arrays t Demo programs

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

Page 123: Lecture 23: Pointers. 2 Lecture Contents: t Pointers and addresses t Pointers and function arguments t Pointers and arrays t Pointer arrays t Demo programs

123Copyright © 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 Node Node

PointerPointer

Linked list

Page 124: Lecture 23: Pointers. 2 Lecture Contents: t Pointers and addresses t Pointers and function arguments t Pointers and arrays t Pointer arrays t Demo programs

124Copyright © 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

Page 125: Lecture 23: Pointers. 2 Lecture Contents: t Pointers and addresses t Pointers and function arguments t Pointers and arrays t Pointer arrays t Demo programs

125Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

Pointers

• Actual address has no meaning for us

• Form: type *variable;

• Example: float *p;

?

P

Page 126: Lecture 23: Pointers. 2 Lecture Contents: t Pointers and addresses t Pointers and function arguments t Pointers and arrays t Pointer arrays t Demo programs

126Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

new Operator

• Actually allocates storage

• Form: new type;

new type [n];

• Example: new float;

Page 127: Lecture 23: Pointers. 2 Lecture Contents: t Pointers and addresses t Pointers and function arguments t Pointers and arrays t Pointer arrays t Demo programs

127Copyright © 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

Page 128: Lecture 23: Pointers. 2 Lecture Contents: t Pointers and addresses t Pointers and function arguments t Pointers and arrays t Pointer arrays t Demo programs

128Copyright © 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;

OutputThe contents of memory cell pointed to by p is 15.5

Page 129: Lecture 23: Pointers. 2 Lecture Contents: t Pointers and addresses t Pointers and function arguments t Pointers and arrays t Pointer arrays t Demo programs

129Copyright © 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 !=

Page 130: Lecture 23: Pointers. 2 Lecture Contents: t Pointers and addresses t Pointers and function arguments t Pointers and arrays t Pointer arrays t Demo programs

130Copyright © 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

Page 131: Lecture 23: Pointers. 2 Lecture Contents: t Pointers and addresses t Pointers and function arguments t Pointers and arrays t Pointer arrays t Demo programs

131Copyright © 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

current voltsp? ?

Page 132: Lecture 23: Pointers. 2 Lecture Contents: t Pointers and addresses t Pointers and function arguments t Pointers and arrays t Pointer arrays t Demo programs

132Copyright © 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;

current voltspAC 115

Page 133: Lecture 23: Pointers. 2 Lecture Contents: t Pointers and addresses t Pointers and function arguments t Pointers and arrays t Pointer arrays t Demo programs

133Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

struct Member Access through a Pointer

• Form: p ->m

• Example: p ->voltscout << p->current << p->volts << endl;

• OutputAC115

Page 134: Lecture 23: Pointers. 2 Lecture Contents: t Pointers and addresses t Pointers and function arguments t Pointers and arrays t Pointer arrays t Demo programs

134Copyright © 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;current voltsp

AC 115

current voltsqAC 115

Page 135: Lecture 23: Pointers. 2 Lecture Contents: t Pointers and addresses t Pointers and function arguments t Pointers and arrays t Pointer arrays t Demo programs

135Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

Pointers and Structs

q ->volts = 220;

q = p;

current voltsAC 220

q

AC 115

AC 220

p q->current q->voltsp->current p->volts

q

Page 136: Lecture 23: Pointers. 2 Lecture Contents: t Pointers and addresses t Pointers and function arguments t Pointers and arrays t Pointer arrays t Demo programs

136Copyright © 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;

Page 137: Lecture 23: Pointers. 2 Lecture Contents: t Pointers and addresses t Pointers and function arguments t Pointers and arrays t Pointer arrays t Demo programs

137Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

Figure 13.1 Heap before and after execution of p - new node;

Page 138: Lecture 23: Pointers. 2 Lecture Contents: t Pointers and addresses t Pointers and function arguments t Pointers and arrays t Pointer arrays t Demo programs

138Copyright © 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;

Page 139: Lecture 23: Pointers. 2 Lecture Contents: t Pointers and addresses t Pointers and function arguments t Pointers and arrays t Pointer arrays t Demo programs

139Copyright © 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

Page 140: Lecture 23: Pointers. 2 Lecture Contents: t Pointers and addresses t Pointers and function arguments t Pointers and arrays t Pointer arrays t Demo programs

140Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

Figure 13.2 Children’s pop beads in a chain

Page 141: Lecture 23: Pointers. 2 Lecture Contents: t Pointers and addresses t Pointers and function arguments t Pointers and arrays t Pointer arrays t Demo programs

141Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

Declaring Nodes

• If a pointer is included in a struct we can connect nodesstruct node{

string word;int count;node *link;

};node *p, *q, *r;

Page 142: Lecture 23: Pointers. 2 Lecture Contents: t Pointers and addresses t Pointers and function arguments t Pointers and arrays t Pointer arrays t Demo programs

142Copyright © 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 count link

Struct of type node

String Integer Address

Page 143: Lecture 23: Pointers. 2 Lecture Contents: t Pointers and addresses t Pointers and function arguments t Pointers and arrays t Pointer arrays t Demo programs

143Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

Connecting Nodes

• Allocate storage of 2 nodesp = new node;q = new node;

• Assignment Statementsp->word = “hat”;p->count = 2;q->word = “top”;q->count = 3;

Page 144: Lecture 23: Pointers. 2 Lecture Contents: t Pointers and addresses t Pointers and function arguments t Pointers and arrays t Pointer arrays t Demo programs

144Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

Figure 13.3 Nodes pointed to by p and q

Page 145: Lecture 23: Pointers. 2 Lecture Contents: t Pointers and addresses t Pointers and function arguments t Pointers and arrays t Pointer arrays t Demo programs

145Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

Connecting Nodes

• Link fields are undefined until assignmentp->link = q;

– Address of q is stored in link field pointed to by p

• Accessing elementsq->word or p->link->word

• Null stored at last link fieldq->link = NULL; or p->link->link = NULL;

Page 146: Lecture 23: Pointers. 2 Lecture Contents: t Pointers and addresses t Pointers and function arguments t Pointers and arrays t Pointer arrays t Demo programs

146Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

Figure 13.4 List with two elements

Page 147: Lecture 23: Pointers. 2 Lecture Contents: t Pointers and addresses t Pointers and function arguments t Pointers and arrays t Pointer arrays t Demo programs

147Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

Inserting a Node

• Create and initialize noder = 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;

Page 148: Lecture 23: Pointers. 2 Lecture Contents: t Pointers and addresses t Pointers and function arguments t Pointers and arrays t Pointer arrays t Demo programs

148Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

Inserting a New Node in a List

Page 149: Lecture 23: Pointers. 2 Lecture Contents: t Pointers and addresses t Pointers and function arguments t Pointers and arrays t Pointer arrays t Demo programs

149Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

Insertion at Head of List

• OldHead points to original list headoldHead = p;

• Point p to a new nodep = new node;

• Connect new list head to old list headp->link = oldHead;

Page 150: Lecture 23: Pointers. 2 Lecture Contents: t Pointers and addresses t Pointers and function arguments t Pointers and arrays t Pointer arrays t Demo programs

150Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

Figure 13.6 Insertion at the head of a list

Page 151: Lecture 23: Pointers. 2 Lecture Contents: t Pointers and addresses t Pointers and function arguments t Pointers and arrays t Pointer arrays t Demo programs

151Copyright © 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 listlast->link = new node;

• Mark end with a NULL (from cstdlib)last->link->link = NULL;

Page 152: Lecture 23: Pointers. 2 Lecture Contents: t Pointers and addresses t Pointers and function arguments t Pointers and arrays t Pointer arrays t Demo programs

152Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

Figure 13.7 Insertion at the end of a list

Page 153: Lecture 23: Pointers. 2 Lecture Contents: t Pointers and addresses t Pointers and function arguments t Pointers and arrays t Pointer arrays t Demo programs

153Copyright © 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

predecessorp->link = r->link;

• Disconnect the node pointed to by r from its successor

r->link = NULL;

• Return node to heapdelete r;

Page 154: Lecture 23: Pointers. 2 Lecture Contents: t Pointers and addresses t Pointers and function arguments t Pointers and arrays t Pointer arrays t Demo programs

154Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

Figure 13.8 Deleting a list node

Page 155: Lecture 23: Pointers. 2 Lecture Contents: t Pointers and addresses t Pointers and function arguments t Pointers and arrays t Pointer arrays t Demo programs

155Copyright © 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 traversehead = head->link;

• Watch use of reference parameters

Page 156: Lecture 23: Pointers. 2 Lecture Contents: t Pointers and addresses t Pointers and function arguments t Pointers and arrays t Pointer arrays t Demo programs

156Copyright © 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 << head->word << " " << head->count << endl;

head = head->link;

}

}

Page 157: Lecture 23: Pointers. 2 Lecture Contents: t Pointers and addresses t Pointers and function arguments t Pointers and arrays t Pointer arrays t Demo programs

157Copyright © 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

Page 158: Lecture 23: Pointers. 2 Lecture Contents: t Pointers and addresses t Pointers and function arguments t Pointers and arrays t Pointer arrays t Demo programs

158Copyright © 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

Page 159: Lecture 23: Pointers. 2 Lecture Contents: t Pointers and addresses t Pointers and function arguments t Pointers and arrays t Pointer arrays t Demo programs

159Copyright © 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&)

Page 160: Lecture 23: Pointers. 2 Lecture Contents: t Pointers and addresses t Pointers and function arguments t Pointers and arrays t Pointer arrays t Demo programs

160Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

Listing 13.2 Using list class

Page 161: Lecture 23: Pointers. 2 Lecture Contents: t Pointers and addresses t Pointers and function arguments t Pointers and arrays t Pointer arrays t Demo programs

161Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

Listing 13.2 Using list class (continued)

Page 162: Lecture 23: Pointers. 2 Lecture Contents: t Pointers and addresses t Pointers and function arguments t Pointers and arrays t Pointer arrays t Demo programs

162Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

Listing 13.2 Using list class (continued)

Page 163: Lecture 23: Pointers. 2 Lecture Contents: t Pointers and addresses t Pointers and function arguments t Pointers and arrays t Pointer arrays t Demo programs

163Copyright © 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

Page 164: Lecture 23: Pointers. 2 Lecture Contents: t Pointers and addresses t Pointers and function arguments t Pointers and arrays t Pointer arrays t Demo programs

164Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

A Stack of Characters

*

C

+

2

s

Page 165: Lecture 23: Pointers. 2 Lecture Contents: t Pointers and addresses t Pointers and function arguments t Pointers and arrays t Pointer arrays t Demo programs

165Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

The C++ stack Class

• Must include stack library#include <stack>

• Declare the stackstack <type> stack-name;

• E.g.stack <string> nameStack;stack <char> s;

Page 166: Lecture 23: Pointers. 2 Lecture Contents: t Pointers and addresses t Pointers and function arguments t Pointers and arrays t Pointer arrays t Demo programs

166Copyright © 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

Page 167: Lecture 23: Pointers. 2 Lecture Contents: t Pointers and addresses t Pointers and function arguments t Pointers and arrays t Pointer arrays t Demo programs

167Copyright © 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

s

C

+

2

s

/

C

+

2

s

Page 168: Lecture 23: Pointers. 2 Lecture Contents: t Pointers and addresses t Pointers and function arguments t Pointers and arrays t Pointer arrays t Demo programs

168Copyright © 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*

s.top

stack after insertion of “*”

C

+

2C + 2

s.top

stack before insertion

Page 169: Lecture 23: Pointers. 2 Lecture Contents: t Pointers and addresses t Pointers and function arguments t Pointers and arrays t Pointer arrays t Demo programs

169Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

Listing 13.4 Header file for template class stackList

Page 170: Lecture 23: Pointers. 2 Lecture Contents: t Pointers and addresses t Pointers and function arguments t Pointers and arrays t Pointer arrays t Demo programs

170Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

Listing 13.4 Header file for template class stackList (continued)

Page 171: Lecture 23: Pointers. 2 Lecture Contents: t Pointers and addresses t Pointers and function arguments t Pointers and arrays t Pointer arrays t Demo programs

171Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

Listing 13.5 Implementation file for template class stackList

Page 172: Lecture 23: Pointers. 2 Lecture Contents: t Pointers and addresses t Pointers and function arguments t Pointers and arrays t Pointer arrays t Demo programs

172Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

Listing 13.5 Implementation file for template class stackList (continued)

Page 173: Lecture 23: Pointers. 2 Lecture Contents: t Pointers and addresses t Pointers and function arguments t Pointers and arrays t Pointer arrays t Demo programs

173Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

Listing 13.5 Implementation file for template class stackList (continued)

Page 174: Lecture 23: Pointers. 2 Lecture Contents: t Pointers and addresses t Pointers and function arguments t Pointers and arrays t Pointer arrays t Demo programs

174Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

Listing 13.5 Implementation file for template class stackList (continued)

Page 175: Lecture 23: Pointers. 2 Lecture Contents: t Pointers and addresses t Pointers and function arguments t Pointers and arrays t Pointer arrays t Demo programs

175Copyright © 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

Page 176: Lecture 23: Pointers. 2 Lecture Contents: t Pointers and addresses t Pointers and function arguments t Pointers and arrays t Pointer arrays t Demo programs

176Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

Figure 13.12 Queue of customers

Page 177: Lecture 23: Pointers. 2 Lecture Contents: t Pointers and addresses t Pointers and function arguments t Pointers and arrays t Pointer arrays t Demo programs

177Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

The C++ queue Class

• Must include queue library#include <queue>

• Declare the stackstack <type> queue-name;

• E.g.stack <string> customers;

Page 178: Lecture 23: Pointers. 2 Lecture Contents: t Pointers and addresses t Pointers and function arguments t Pointers and arrays t Pointer arrays t Demo programs

178Copyright © 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

Page 179: Lecture 23: Pointers. 2 Lecture Contents: t Pointers and addresses t Pointers and function arguments t Pointers and arrays t Pointer arrays t Demo programs

179Copyright © 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

Page 180: Lecture 23: Pointers. 2 Lecture Contents: t Pointers and addresses t Pointers and function arguments t Pointers and arrays t Pointer arrays t Demo programs

180Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

Listing 13.6 Header file for queue template class

Page 181: Lecture 23: Pointers. 2 Lecture Contents: t Pointers and addresses t Pointers and function arguments t Pointers and arrays t Pointer arrays t Demo programs

181Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

Listing 13.6 Header file for queue template class (continued)

Page 182: Lecture 23: Pointers. 2 Lecture Contents: t Pointers and addresses t Pointers and function arguments t Pointers and arrays t Pointer arrays t Demo programs

182Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

Listing 13.6 Header file for queue template class (continued)

Page 183: Lecture 23: Pointers. 2 Lecture Contents: t Pointers and addresses t Pointers and function arguments t Pointers and arrays t Pointer arrays t Demo programs

183Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

Listing 13.7 Implementation file for queue template class

Page 184: Lecture 23: Pointers. 2 Lecture Contents: t Pointers and addresses t Pointers and function arguments t Pointers and arrays t Pointer arrays t Demo programs

184Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

Listing 13.7 Implementation file for queue template class (continued)

Page 185: Lecture 23: Pointers. 2 Lecture Contents: t Pointers and addresses t Pointers and function arguments t Pointers and arrays t Pointer arrays t Demo programs

185Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

Listing 13.7 Implementation file for queue template class (continued)

Page 186: Lecture 23: Pointers. 2 Lecture Contents: t Pointers and addresses t Pointers and function arguments t Pointers and arrays t Pointer arrays t Demo programs

186Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

Listing 13.7 Implementation file for queue template class (continued)

Page 187: Lecture 23: Pointers. 2 Lecture Contents: t Pointers and addresses t Pointers and function arguments t Pointers and arrays t Pointer arrays t Demo programs

187Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

Listing 13.7 Implementation file for queue template class (continued)

Page 188: Lecture 23: Pointers. 2 Lecture Contents: t Pointers and addresses t Pointers and function arguments t Pointers and arrays t Pointer arrays t Demo programs

188Copyright © 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

Page 189: Lecture 23: Pointers. 2 Lecture Contents: t Pointers and addresses t Pointers and function arguments t Pointers and arrays t Pointer arrays t Demo programs

189Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

Figure 13.13 Binary trees

Page 190: Lecture 23: Pointers. 2 Lecture Contents: t Pointers and addresses t Pointers and function arguments t Pointers and arrays t Pointer arrays t Demo programs

190Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

Additional Tree Terminology

• Disjoint subtrees

• parent

• children

• siblings

• ancestor

• descendant

Page 191: Lecture 23: Pointers. 2 Lecture Contents: t Pointers and addresses t Pointers and function arguments t Pointers and arrays t Pointer arrays t Demo programs

191Copyright © 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

Page 192: Lecture 23: Pointers. 2 Lecture Contents: t Pointers and addresses t Pointers and function arguments t Pointers and arrays t Pointer arrays t Demo programs

192Copyright © 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

elsesearch right subtree

Page 193: Lecture 23: Pointers. 2 Lecture Contents: t Pointers and addresses t Pointers and function arguments t Pointers and arrays t Pointer arrays t Demo programs

193Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

Figure 13.14 Searching for key 42

Page 194: Lecture 23: Pointers. 2 Lecture Contents: t Pointers and addresses t Pointers and function arguments t Pointers and arrays t Pointer arrays t Demo programs

194Copyright © 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

Page 195: Lecture 23: Pointers. 2 Lecture Contents: t Pointers and addresses t Pointers and function arguments t Pointers and arrays t Pointer arrays t Demo programs

195Copyright © 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

elseinsert new item in right subtree

Page 196: Lecture 23: Pointers. 2 Lecture Contents: t Pointers and addresses t Pointers and function arguments t Pointers and arrays t Pointer arrays t Demo programs

196Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

Figure 13.15 Building a binary search tree

Page 197: Lecture 23: Pointers. 2 Lecture Contents: t Pointers and addresses t Pointers and function arguments t Pointers and arrays t Pointer arrays t Demo programs

197Copyright © 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

Page 198: Lecture 23: Pointers. 2 Lecture Contents: t Pointers and addresses t Pointers and function arguments t Pointers and arrays t Pointer arrays t Demo programs

198Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

13.7 Binary Search Tree ADT

• Attributes– root pointer to the tree root

• Member Functions– binaryTree a constructor– insert inserts an item– retrieve retrieves an item– search locates a node for a key– display displays a tree

Page 199: Lecture 23: Pointers. 2 Lecture Contents: t Pointers and addresses t Pointers and function arguments t Pointers and arrays t Pointer arrays t Demo programs

199Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

Listing 13.8 Template class specification for tree<treeElement>

Page 200: Lecture 23: Pointers. 2 Lecture Contents: t Pointers and addresses t Pointers and function arguments t Pointers and arrays t Pointer arrays t Demo programs

200Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

Listing 13.8 Template class specification for tree<treeElement> (continued)

Page 201: Lecture 23: Pointers. 2 Lecture Contents: t Pointers and addresses t Pointers and function arguments t Pointers and arrays t Pointer arrays t Demo programs

201Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

Listing 13.8 Template class specification for tree<treeElement> (continued)

Page 202: Lecture 23: Pointers. 2 Lecture Contents: t Pointers and addresses t Pointers and function arguments t Pointers and arrays t Pointer arrays t Demo programs

202Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

Listing 13.9 Member functions binaryTree and search

Page 203: Lecture 23: Pointers. 2 Lecture Contents: t Pointers and addresses t Pointers and function arguments t Pointers and arrays t Pointer arrays t Demo programs

203Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

Listing 13.9 Member functions binaryTree and search (continued)

Page 204: Lecture 23: Pointers. 2 Lecture Contents: t Pointers and addresses t Pointers and function arguments t Pointers and arrays t Pointer arrays t Demo programs

204Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

Listing 13.10 Member functions insert

Page 205: Lecture 23: Pointers. 2 Lecture Contents: t Pointers and addresses t Pointers and function arguments t Pointers and arrays t Pointer arrays t Demo programs

205Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

Listing 13.10 Member functions insert (continued)

Page 206: Lecture 23: Pointers. 2 Lecture Contents: t Pointers and addresses t Pointers and function arguments t Pointers and arrays t Pointer arrays t Demo programs

206Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

Listing 13.11 Member functions display

Page 207: Lecture 23: Pointers. 2 Lecture Contents: t Pointers and addresses t Pointers and function arguments t Pointers and arrays t Pointer arrays t Demo programs

207Copyright © 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)

Page 208: Lecture 23: Pointers. 2 Lecture Contents: t Pointers and addresses t Pointers and function arguments t Pointers and arrays t Pointer arrays t Demo programs

208Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

Values of N versus log2N

N log2N

32 5

64 6

128 7

256 8

512 9

1024 10

Page 209: Lecture 23: Pointers. 2 Lecture Contents: t Pointers and addresses t Pointers and function arguments t Pointers and arrays t Pointer arrays t Demo programs

209Copyright © 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

Page 210: Lecture 23: Pointers. 2 Lecture Contents: t Pointers and addresses t Pointers and function arguments t Pointers and arrays t Pointer arrays t Demo programs

210

Thank You

For

Your Attention