Lecture 23: Pointers. 2 Lecture Contents: t Pointers and addresses t Pointers and function arguments...

Preview:

Citation preview

Lecture 23:Pointers

2

Lecture Contents:

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

3

Pointer basics

Pointers are variables that contain address values.

Pointers are variables used to store address values.

The basic concept of a pointer is:

indirect access to data values

4

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)

5

Pointer basics

Direct access to data values:

int alpha=5; int beta;

beta = alpha;

6

Pointer basics

Indirect access to data values:

int alpha=5, beta, *ptr;

ptr = α

beta = *ptr;

7

Pointer basics

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

// & - address of operatorptr = α

//indirection or dereferencing operator

beta = *ptr;

8

Declaration of pointers

How to define (declare) pointers as variables?

int *p1;

p1 is a variable whose memory space will be used to store addresses of integer data.

9

Declaration of pointers

How to define (declare) pointers as variables?

char *p2;

p2 is a variable whose memory space will be used to store addresses of character data.

10

Declaration of pointers

How to define (declare) pointers as variables?

double *p3;

p3 is a variable whose memory space will be used to store addresses of double data.

11

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

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

13

More on Pointers

Pointers and Addresses 

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

15

More on Pointers and Arrays

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

char *pmessage;

pmessage = “Now is the time!”;

16

More on Pointers and Arrays

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

int I=0;

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

{

cout << endl << amessage[I];

I++;

}

17

More on Pointers and Arrays

char *pmessage = “Now is the time!”; while(*pmessage != ‘\0’) {

cout << *pmessage; pmessage++; }

=================================================== char *pmessage = “Now is the time!”; char *q; q = pmessage + strlen(pmessage); while( pmessage < q ) {

cout << *pmessage; pmessage++; }

18

More on Pointers

Array of pointers

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

“Nov”, “Dec” };

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

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

19

More on Pointers

Multidimensional arrays and pointers

int a[10][20];

int *b[10];

20

Pointers and function arguments

Problem: function to swap contents of two variables: void swap(int, int);

swap(a, b);

void swap(int p1, int p2){

int temp; temp=p1; p1=p2; p2=temp;}

21

Pointers and function arguments

The solution: addresses specified as actual arguments void swap(int *, int *);

swap(&a, &b);

void swap(int *p1, int *p2){

int temp; temp=*p1; *p1=*p2; *p2=temp;}

22

More on Pointers

Address arithmetic:

char a[10];

a ≡ a + 0 ≡ &a[0]

a + I ≡ &a[I]

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

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

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

25

More on Pointers

Extract from Friedman/Koffman, chapter 13

Pointers & Dynamic Data Structures

Chapter 13

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

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

29

Pointers

Actual address has no meaning

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

?

P

30

new Operator

Actually allocates storage

Form: new type;

new type [n];

Example: new float;

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

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

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

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

35

Effect on new on the Heap

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;

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

38

Children’s Beads

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;

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

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;

42

Figure 13.3

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;

44

Connecting Nodes

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;

46

Inserting a New Node in a List

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;

48

Insertion at Head of List

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;

50

Insertion at End of List

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;

52

Deleting a Node

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

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;

}

}

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

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

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

58

StackList.h

bool push (const stackElement& x); bool pop (stackElement& x); bool peek (stackElement& x) const; bool isEmpty () const; bool isFull () const;private: struct stackNode { stackElement item;

stackNode* next; };// Data member

stackNode* top;};

#endif // STACK_LIST_H

59

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

60

StackList.cpp

// Push an element onto the stack

// Pre: The element x is defined.

// Post: If there is space on the heap,

// the item is pushed onto the stack and

// true is returned. Otherwise, the

// stack is unchanged and false is

// returned.

61

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

62

StackList.cpp

// Pop an element off the stack

// Pre: none

// Post: If the stack is not empty, the value

// at the top of the stack is removed, its

// value is placed in x, and true is returned.

// If stack empty, x is not defined and false returned.

63

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

64

StackList.cpp

// Get top element from stack without popping

// Pre: none

// Post: If the stack is not empty, the value

// at the top is copied into x and true is

// returned. If the stack is empty, x is not

// defined and false is returned. In

// either case, the stack is not changed.

65

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

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

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

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

69

Queue of Customers

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

71

Queue.h

bool insert (const queueElement& x); bool remove (queueElement& x);

bool isEmpty ();int getSize ();

private: struct queueNode { queueElement item;

queueNode* next; };queueNode* front;

queueNode* rear; int numItems; };#endif // QUEUE_H

72

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

73

Queue.cpp

{

numItems = 0;

front = NULL;

rear = NULL;

}

// Insert an element into the queue

// Pre : none

// Post: If heap space is available, the

// value x is inserted at the rear of the queue

// and true is returned. Otherwise, the queue is

// not changed and false is returned.

74

Queue.cpp

// Insert an element into the queue

// Pre : none

// Post: If heap space is available, the

// value x is inserted at the rear of the queue

// and true is returned. Otherwise, the queue is

// not changed and false is returned.

75

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

76

Queue.cpp

// Remove an element from the queue

// Pre : none

// Post: If the queue is not empty, the value at

// the front of the queue is removed, its value

// is placed in x, and true is returned. If the

// queue is empty, x is not defined and false

// is returned.

77

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

78

Queue.cpp

// Test whether queue is empty

template<class queueElement>

bool queue<queueElement>::isEmpty()

{

return (numItems == 0);

}

79

Queue.cpp

// Returns queue size

template<class queueElement>

int queue<queueElement>::getSize()

{

return numItems;

}

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

81

Binary Tree

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

83

Searching Algorithm

if (tree is empty)

target is not in the tree

else if (the target key is the root)

target found in root

else if (target key smaller than the root’s key)

search left sub-tree

else

search right sub-tree

84

Searching for Key 42

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

86

Algorithm for Insertion

if (tree is empty)

insert new item as root

else if (root key matches item)

skip insertion duplicate key

else if (new key is smaller than root)

insert in left sub-tree

else

insert in right sub-tree

87

Figure 13.18 Building a Tree

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

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

90

Example of traversal

– Tree is empty - return from displaying right sub-tree node is 10

– Return from displaying left sub-tree of node 20– Display item with key 20– Display right sub-tree of node 20– Display left sub-tree of node 30– Tree is empty - return from displaying left sub-

tree of node 30– Display item with key 30

91

Example of traversal

– Display right sub-tree of node 30– Tree is empty - return from displaying right

sub-tree of node 30– Return from displaying right sub-tree of node

20– Return from displaying left sub-tree of node 40– Display item with key 40– Display right sub-tree of node 40

92

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

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

{

94

BinaryTree.h

public: // Member functions ... // CREATE AN EMPTY TREE binTree (); // INSERT AN ELEMENT INTO THE TREE bool insert (const treeElement& el );

// RETRIEVE AN ELEMENT FROM THE TREE bool retrieve (treeElement& el ) const;

// SEARCH FOR AN ELEMENT IN THE TREE bool search (const treeElement& el ) const;

// DISPLAY A TREE void display () const;

95

BinaryTree.h

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

};

96

BinaryTree.h

// Data member .... treeNode* root; // Member functions ... // Searches a subtree for a key bool search (treeNode*, const treeElement&) const; // Inserts an item in a subtree bool insert (treeNode*&, const treeElement&) const; // Retrieves an item in a subtree bool retrieve (treeNode*, treeElement&) const;

// Displays a subtree void display (treeNode*) const; };#endif // BIN_TREE_H

97

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

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

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)

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

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

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

103

BinaryTree.cpp

// Check for empty tree. if (aRoot == NULL) { // Attach new node aRoot = new treeNode; aRoot->left = NULL; aRoot->right = NULL; aRoot->info = el; return true; } else if (el == aRoot->info) return false;

104

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.

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

106

BinaryTree.cpp

{

if (aRoot != NULL)

{ // recursive step

display(aRoot->left);

cout << aRoot->info << endl;

display(aRoot->right);

}

} // display

107

BinaryTree.cpp

// Insert member functions retrieve.

template<class treeElement>

bool binaryTree<treeElement>::retrieve

(const treeElement& el) const

{

return retrieve(root, el);

} // retrieve

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

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)

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

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.

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;

113

Exercise 23.1

char str[] = “AUBG Blagoevgrad”;

void main(){ int I=0;

cout << endl << str << endl;while (str[I] != ‘\0’){

cout << endl << str[I];I++;

}}

114

Exercise 23.1

char str[] = “AUBG Blagoevgrad”;

void main(){ char *p = str;

cout << endl << str << endl << p << endl;while ( *p != ‘\0’){

cout << endl << *p;p++;

}}

115

Exercise 25.1-25.6

Build programs based on pointers:

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

116

Exercise 23.1

char str[] = “AUBG Blagoevgrad”; int strlenm(char m[]);

void main(){

cout << endl << strlenm(str) << endl;}int strlenm(char m[]){

int I=0, len;while (m[I] != 0x00) I++;len = I;return len;

}

117

Exercise 23.1

char str[] = “AUBG Blagoevgrad”; int strlenm(char *pm);

void main(){

char *p = str;cout << endl << strlenm(str) << “ “ << strlenm(p) << endl;

}int strlenm(char *pm){

int len = 0;while (*pm != 0x00) { Ien++; pm++; )return len;

}

118

Exercise 25.1-25.6

Build programs based on pointers:

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

119

Exercise 23.1

char str[] = “AUBG Blagoevgrad”;

void copym(char dst[], char src[]);

void main()

{ char newstr[20];

copym(newstr, str);

cout << endl << newstr << endl;

}

void copym(char dst[], char src[])

{

int I=0;

while( ( dst[I] = src[I] ) != ‘\0’ ) I++;

}

120

Exercise 23.1

char str[] = “AUBG Blagoevgrad”;

void copym(char *dst, char *src);

void main()

{ char *newstr; newstr = new char[20];

copym(newstr, str);

cout << endl << newstr << endl;

}

void copym(char *dst, char *src)

{

while( ( *dst = *src ) != ‘\0’ ) { dst++; src++; }

}

121

Before lecture end

Lecture:Pointers

More to read:

Friedman/Koffman, Chapter 13

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

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

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

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

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

new Operator

• Actually allocates storage

• Form: new type;

new type [n];

• Example: new float;

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

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

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

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

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

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

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

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

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

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;

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

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

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;

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

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

Figure 13.2 Children’s pop beads in a chain

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;

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

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;

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

Figure 13.3 Nodes pointed to by p and q

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;

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

Figure 13.4 List with two elements

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;

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

Inserting a New Node in a List

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;

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

Figure 13.6 Insertion at the head of a list

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;

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

Figure 13.7 Insertion at the end of a list

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;

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

Figure 13.8 Deleting a list node

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

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;

}

}

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

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

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

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

Listing 13.2 Using list class

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

Listing 13.2 Using list class (continued)

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

Listing 13.2 Using list class (continued)

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

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

A Stack of Characters

*

C

+

2

s

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;

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

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

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

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

Listing 13.4 Header file for template class stackList

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

Listing 13.4 Header file for template class stackList (continued)

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

Listing 13.5 Implementation file for template class stackList

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

Listing 13.5 Implementation file for template class stackList (continued)

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

Listing 13.5 Implementation file for template class stackList (continued)

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

Listing 13.5 Implementation file for template class stackList (continued)

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

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

Figure 13.12 Queue of customers

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;

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

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

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

Listing 13.6 Header file for queue template class

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

Listing 13.6 Header file for queue template class (continued)

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

Listing 13.6 Header file for queue template class (continued)

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

Listing 13.7 Implementation file for queue template class

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

Listing 13.7 Implementation file for queue template class (continued)

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

Listing 13.7 Implementation file for queue template class (continued)

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

Listing 13.7 Implementation file for queue template class (continued)

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

Listing 13.7 Implementation file for queue template class (continued)

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

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

Figure 13.13 Binary trees

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

Additional Tree Terminology

• Disjoint subtrees

• parent

• children

• siblings

• ancestor

• descendant

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

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

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

Figure 13.14 Searching for key 42

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

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

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

Figure 13.15 Building a binary search tree

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

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

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

Listing 13.8 Template class specification for tree<treeElement>

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

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

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

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

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

Listing 13.9 Member functions binaryTree and search

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

Listing 13.9 Member functions binaryTree and search (continued)

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

Listing 13.10 Member functions insert

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

Listing 13.10 Member functions insert (continued)

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

Listing 13.11 Member functions display

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)

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

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

210

Thank You

For

Your Attention

Recommended