0% found this document useful (0 votes)
33 views74 pages

Chapter 17 - Data Structures

The document discusses different data structures including linked lists. It describes how linked lists are made up of self-referential nodes connected by pointers. The document provides code examples for a template linked list class with functions for inserting and removing nodes from the front and back of the list.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
33 views74 pages

Chapter 17 - Data Structures

The document discusses different data structures including linked lists. It describes how linked lists are made up of self-referential nodes connected by pointers. The document provides code examples for a template linked list class with functions for inserting and removing nodes from the front and back of the list.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 74

1

Chapter 17 - Data Structures


Outline
17.1 Introduction
17.2 Self-Referential Classes
17.3 Dynamic Memory Allocation and Data Structures
17.4 Linked Lists
17.5 Stacks
17.6 Queues
17.7 Trees

 2003 Prentice Hall, Inc. All rights reserved.


2

17.1 Introduction

• Fixed-size data structures


– Arrays, structs
• Dynamic data structures
– Grow and shrink as program runs
– Linked lists
• Insert/remove items anywhere
– Stacks
• Insert/remove from top of stack
– Queues
• Like a line, insert at back, remove from front
– Binary trees
• High-speed searching/sorting of data

 2003 Prentice Hall, Inc. All rights reserved.


3

17.2 Self-Referential Classes

• Self-referential class
– Has pointer to object of same class
– Link together to form useful data structures
• Lists, stacks, queues, trees
– Terminated with NULL pointer

15 10

Data member
and pointer NULL pointer (points to nothing)

 2003 Prentice Hall, Inc. All rights reserved.


4

17.2 Self-Referential Classes

• Sample code
class Node {
public:
Node( int );
void setData( int );
int getData() const;
void setNextPtr( Node * );
const Node *getNextPtr() const;
private:
int data;
Node *nextPtr;
};

• Pointer to object called a link


– nextPtr points to a Node

 2003 Prentice Hall, Inc. All rights reserved.


5
17.3 Dynamic Memory Allocation and Data
Structures
• Dynamic memory allocation
– Obtain and release memory during program execution
– Create and remove nodes
• Operator new
– Takes type of object to create
– Returns pointer to newly created object
• Node *newPtr = new Node( 10 );
• Returns bad_alloc if not enough memory
• 10 is the node's object data

 2003 Prentice Hall, Inc. All rights reserved.


6
17.3 Dynamic Memory Allocation and Data
Structures
• Operator delete
– delete newPtr;
– Deallocates memory allocated by new, calls destructor
– Memory returned to system, can be used in future
• newPtr not deleted, only the space it points to

 2003 Prentice Hall, Inc. All rights reserved.


7

17.4 Linked Lists

• Linked list
– Collection of self-referential class objects (nodes) connected
by pointers (links)
– Accessed using pointer to first node of list
• Subsequent nodes accessed using the links in each node
– Link in last node is null (zero)
• Indicates end of list
– Data stored dynamically
• Nodes created as necessary
• Node can have data of any type

 2003 Prentice Hall, Inc. All rights reserved.


8

17.4 Linked Lists

 2003 Prentice Hall, Inc. All rights reserved.


 2003 Prentice Hall, Inc. All rights reserved.
 2003 Prentice Hall, Inc. All rights reserved.
 2003 Prentice Hall, Inc. All rights reserved.
12

Insert at back
a) firstPtr lastPtr newPtr

12 7 11 5

b) firstPtr lastPtr newPtr

12 7 11 5

lastPtr->nextPtr = newPtr

lastPtr = newPtr
If list empty, then
firstPtr = lastPtr = newPtr

 2003 Prentice Hall, Inc. All rights reserved.


13

Remove from front


a) firstPtr lastPtr

12 7 11 5

b) firstPtr lastPtr

tempPtr = firstPtr

12 7 11 5

tempPtr
firstPtr = firstPtr->next
If there are no more nodes,
firstPtr = lastPtr = 0

delete tempPtr

 2003 Prentice Hall, Inc. All rights reserved.


14

Remove from back


"Walk" list until get next-to-last node, until
currentPtr->nextPtr = lastPtr
a) firstPtr lastPtr

12 7 11 5

b) firstPtr currentPtr lastPtr

12 7 11 5

tempPtr = lastPtr
lastPtr = currentPtr
tempPtr

delete tempPtr
 2003 Prentice Hall, Inc. All rights reserved.
15

17.4 Linked Lists

• Upcoming program has two class templates


– Create two class templates
– ListNode
• data (type depends on class template)
• nextPtr
– List
• Linked list of ListNode objects
• List manipulation functions
– insertAtFront
– insertAtBack
– removeFromFront
– removeFromBack

 2003 Prentice Hall, Inc. All rights reserved.


16
1 // Fig. 17.3: listnode.h
2 // Template ListNode class definition.
Outline
3 #ifndef LISTNODE_H
4 #define LISTNODE_H
listnode.h (1 of 2)
5
Template class ListNode.
6 // forward declaration of class List
7 template< class NODETYPE > class List;
The type of member data
8 depends on how the class
9 template< class NODETYPE> template is used.
10 class ListNode {
11 friend class List< NODETYPE >; // make List a friend
12
13 public:
14 ListNode( const NODETYPE & ); // constructor
15 NODETYPE getData() const; // return data in node
16
17 private:
18 NODETYPE data; // data
19 ListNode< NODETYPE > *nextPtr; // next node in list
20
21 }; // end class ListNode
22

 2003 Prentice Hall, Inc.


All rights reserved.
17
23 // constructor
24 template< class NODETYPE>
Outline
25 ListNode< NODETYPE >::ListNode( const NODETYPE &info )
26 : data( info ),
listnode.h (2 of 2)
27 nextPtr( 0 )
28 {
29 // empty body
30
31 } // end ListNode constructor
32
33 // return copy of data in node
34 template< class NODETYPE >
35 NODETYPE ListNode< NODETYPE >::getData() const
36 {
37 return data;
38
39 } // end function getData
40
41 #endif

 2003 Prentice Hall, Inc.


All rights reserved.
18
1 // Fig. 17.4: list.h
2 // Template List class definition.
Outline
3 #ifndef LIST_H
4 #define LIST_H
list.h (1 of 9)
5
6 #include <iostream>
7
8 using std::cout;
9
10 #include <new>
11 #include "listnode.h" // ListNode class definition
12
13 template< class NODETYPE >
14 class List {
15
16 public:
17 List(); // constructor
18 ~List(); // destructor
19 void insertAtFront( const NODETYPE & );
20 void insertAtBack( const NODETYPE & );
21 bool removeFromFront( NODETYPE & );
22 bool removeFromBack( NODETYPE & );
23 bool isEmpty() const;
24 void print() const;
25

 2003 Prentice Hall, Inc.


All rights reserved.
19
26 private:
27 ListNode< NODETYPE > *firstPtr; // pointer to first node
Outline
28 ListNode< NODETYPE > *lastPtr; // pointer to last node
29
list.h (2 of 9)
30 // utility function to allocate new node
31 ListNode< NODETYPE > *getNewNode( const NODETYPE & );
32
33 }; // end class List Each List has a firstPtr
34 and lastPtr.
35 // default constructor
36 template< class NODETYPE >
37 List< NODETYPE >::List()
38 : firstPtr( 0 ),
39 lastPtr( 0 )
40 {
41 // empty body
42
43 } // end List constructor
44

 2003 Prentice Hall, Inc.


All rights reserved.
20
45 // destructor
46 template< class NODETYPE >
Outline
47 List< NODETYPE >::~List()
48 {
list.h (3 of 9)
49 if ( !isEmpty() ) { // List is not empty
50 cout << "Destroying nodes ...\n";
51
52 ListNode< NODETYPE > *currentPtr = firstPtr;
53 ListNode< NODETYPE > *tempPtr;
54
55 while ( currentPtr != 0 ) { // delete remaining nodes
56 tempPtr = currentPtr;
57 cout << tempPtr->data << '\n';
58 currentPtr = currentPtr->nextPtr;
59 delete tempPtr;
60
61 } // end while
62
63 } // end if
64
65 cout << "All nodes destroyed\n\n";
66
67 } // end List destructor
68

 2003 Prentice Hall, Inc.


All rights reserved.
21
69 // insert node at front of list
70 template< class NODETYPE >
Outline
71 void List< NODETYPE >::insertAtFront( const NODETYPE &value )
72 {
list.h (4 of 9)
73 ListNode< NODETYPE > *newPtr = getNewNode( value );
74
75 if ( isEmpty() ) // List is empty
76 firstPtr = lastPtr = newPtr;
77 Insert a new node as described
78 else { // List is not empty
in the previous diagrams.
79 newPtr->nextPtr = firstPtr;
80 firstPtr = newPtr;
81
82 } // end else
83
84 } // end function insertAtFront
85

 2003 Prentice Hall, Inc.


All rights reserved.
22
86 // insert node at back of list
87 template< class NODETYPE >
Outline
88 void List< NODETYPE >::insertAtBack( const NODETYPE &value )
89 {
list.h (5 of 9)
90 ListNode< NODETYPE > *newPtr = getNewNode( value );
91
92 if ( isEmpty() ) // List is empty
93 firstPtr = lastPtr = newPtr;
94
95 else { // List is not empty
96 lastPtr->nextPtr = newPtr;
97 lastPtr = newPtr;
98
99 } // end else
100
101 } // end function insertAtBack
102

 2003 Prentice Hall, Inc.


All rights reserved.
23
103 // delete node from front of list
104 template< class NODETYPE >
Outline
105 bool List< NODETYPE >::removeFromFront( NODETYPE &value )
106 {
list.h (6 of 9)
107 if ( isEmpty() ) // List is empty
108 return false; // delete unsuccessful
109
110 else {
111 ListNode< NODETYPE > *tempPtr = firstPtr;
112
113 if ( firstPtr == lastPtr )
114 firstPtr = lastPtr = 0;
115 else
116 firstPtr = firstPtr->nextPtr;
117
118 value = tempPtr->data; // data being removed
119 delete tempPtr;
120
121 return true; // delete successful
122
123 } // end else
124
125 } // end function removeFromFront
126

 2003 Prentice Hall, Inc.


All rights reserved.
24
127 // delete node from back of list
128 template< class NODETYPE >
Outline
129 bool List< NODETYPE >::removeFromBack( NODETYPE &value )
130 {
list.h (7 of 9)
131 if ( isEmpty() )
132 return false; // delete unsuccessful
133
134 else {
135 ListNode< NODETYPE > *tempPtr = lastPtr;
136
137 if ( firstPtr == lastPtr )
138 firstPtr = lastPtr = 0;
139 else {
140 ListNode< NODETYPE > *currentPtr = firstPtr;
141
142 // locate second-to-last element
143 while ( currentPtr->nextPtr != lastPtr )
144 currentPtr = currentPtr->nextPtr;
145
146 lastPtr = currentPtr;
147 currentPtr->nextPtr = 0;
148
149 } // end else
150
151 value = tempPtr->data;
152 delete tempPtr;
153

 2003 Prentice Hall, Inc.


All rights reserved.
25
154 return true; // delete successful
155
Outline
156 } // end else
157
list.h (8 of 9)
158 } // end function removeFromBack
159
160 // is List empty?
161 template< class NODETYPE >
162 bool List< NODETYPE >::isEmpty() const
163 {
164 return firstPtr == 0;
165
166 } // end function isEmpty
167
Note use of new operator to
168 // return pointer to newly allocated node
169 template< class NODETYPE >
dynamically allocate a node.
170 ListNode< NODETYPE > *List< NODETYPE >::getNewNode(
171 const NODETYPE &value )
172 {
173 return new ListNode< NODETYPE >( value );
174
175 } // end function getNewNode
176

 2003 Prentice Hall, Inc.


All rights reserved.
26
177 // display contents of List
178 template< class NODETYPE >
Outline
179 void List< NODETYPE >::print() const
180 {
list.h (9 of 9)
181 if ( isEmpty() ) {
182 cout << "The list is empty\n\n";
183 return;
184
185 } // end if
186
187 ListNode< NODETYPE > *currentPtr = firstPtr;
188
189 cout << "The list is: ";
190
191 while ( currentPtr != 0 ) {
192 cout << currentPtr->data << ' ';
193 currentPtr = currentPtr->nextPtr;
194
195 } // end while
196
197 cout << "\n\n";
198
199 } // end function print
200
201 #endif

 2003 Prentice Hall, Inc.


All rights reserved.
27
1 // Fig. 17.5: fig17_05.cpp
2 // List class test program.
Outline
3 #include <iostream>
4
fig17_05.cpp
5 using std::cin;
(1 of 4)
6 using std::endl;
7
8 #include <string> Program to give user a menu
9 to add/remove nodes from a
10 using std::string;
list.
11
12 #include "list.h" // List class definition
13
14 // function to test a List
15 template< class T >
16 void testList( List< T > &listObject, const string &typeName )
17 {
18 cout << "Testing a List of " << typeName << " values\n";
19
20 instructions(); // display instructions
21
22 int choice;
23 T value;
24

 2003 Prentice Hall, Inc.


All rights reserved.
28
25 do {
26 cout << "? ";
Outline
27 cin >> choice;
28
fig17_05.cpp
29 switch ( choice ) {
(2 of 4)
30 case 1:
31 cout << "Enter " << typeName << ": ";
32 cin >> value;
33 listObject.insertAtFront( value );
34 listObject.print();
35 break;
36
37 case 2:
38 cout << "Enter " << typeName << ": ";
39 cin >> value;
40 listObject.insertAtBack( value );
41 listObject.print();
42 break;
43
44 case 3:
45 if ( listObject.removeFromFront( value ) )
46 cout << value << " removed from list\n";
47
48 listObject.print();
49 break;
50

 2003 Prentice Hall, Inc.


All rights reserved.
29
51 case 4:
52 if ( listObject.removeFromBack( value ) )
Outline
53 cout << value << " removed from list\n";
54
fig17_05.cpp
55 listObject.print();
(3 of 4)
56 break;
57
58 } // end switch
59
60 } while ( choice != 5 ); // end do/while
61
62 cout << "End list test\n\n";
63
64 } // end function testList
65
66 // display program instructions to user
67 void instructions()
68 {
69 cout << "Enter one of the following:\n"
70 << " 1 to insert at beginning of list\n"
71 << " 2 to insert at end of list\n"
72 << " 3 to delete from beginning of list\n"
73 << " 4 to delete from end of list\n"
74 << " 5 to end list processing\n";
75
76 } // end function instructions

 2003 Prentice Hall, Inc.


All rights reserved.
30
77
78 int main()
Outline
79 {
80 // test List of int values
fig17_05.cpp
81 List< int > integerList;
(4 of 4)
82 testList( integerList, "integer" );
83
84 // test List of double values
85 List< double > doubleList;
86 testList( doubleList, "double" );
87
88 return 0;
89
90 } // end main

 2003 Prentice Hall, Inc.


All rights reserved.
31
Testing a List of integer values
Enter one of the following:
Outline
1 to insert at beginning of list
2 to insert at end of list
fig17_05.cpp
3 to delete from beginning of list
output (1 of 4)
4 to delete from end of list
5 to end list processing
? 1
Enter integer: 1
The list is: 1

? 1
Enter integer: 2
The list is: 2 1
 
? 2
Enter integer: 3
The list is: 2 1 3
 
? 2
Enter integer: 4
The list is: 2 1 3 4
 

 2003 Prentice Hall, Inc.


All rights reserved.
32
? 3
2 removed from list
Outline
The list is: 1 3 4
 
fig17_05.cpp
? 3
output (2 of 4)
1 removed from list
The list is: 3 4

? 4
4 removed from list
The list is: 3
 
? 4
3 removed from list
The list is empty
 
? 5
End list test

 2003 Prentice Hall, Inc.


All rights reserved.
33
Testing a List of double values
Enter one of the following:
Outline
1 to insert at beginning of list
2 to insert at end of list
fig17_05.cpp
3 to delete from beginning of list
output (3 of 4)
4 to delete from end of list
5 to end list processing
? 1
Enter double: 1.1
The list is: 1.1
 
? 1
Enter double: 2.2
The list is: 2.2 1.1
 
? 2
Enter double: 3.3
The list is: 2.2 1.1 3.3
 
? 2
Enter double: 4.4
The list is: 2.2 1.1 3.3 4.4
 
? 3
2.2 removed from list
The list is: 1.1 3.3 4.4

 2003 Prentice Hall, Inc.


All rights reserved.
34
? 3
1.1 removed from list
Outline
The list is: 3.3 4.4
 
fig17_05.cpp
? 4
output (4 of 4)
4.4 removed from list
The list is: 3.3
 
? 4
3.3 removed from list
The list is empty
 
? 5
End list test
 
All nodes destroyed
 
All nodes destroyed

 2003 Prentice Hall, Inc.


All rights reserved.
35

17.4 Linked Lists

• Types of linked lists


– Singly linked list (used in example)
• Pointer to first node
• Travel in one direction (null-terminated)
– Circular, singly-linked
• As above, but last node points to first
– Doubly-linked list
• Each node has a forward and backwards pointer
• Travel forward or backward
• Last node null-terminated
– Circular, double-linked
• As above, but first and last node joined

 2003 Prentice Hall, Inc. All rights reserved.


36

17.5 Stacks

• Stack
– Nodes can be added/removed from top
• Constrained version of linked list
• Like a stack of plates
– Last-in, first-out (LIFO) data structure
– Bottom of stack has null link
• Stack operations
– Push: add node to top
– Pop: remove node from top
• Stores value in reference variable

 2003 Prentice Hall, Inc. All rights reserved.


37

17.5 Stacks

• Stack applications
– Function calls: know how to return to caller
• Return address pushed on stack
C
• Most recent function call on top B B B
• If function A calls B which calls C: A A A A A

– Used to store automatic variables


• Popped of stack when no longer needed
– Used by compilers
• Example in the exercises in book

 2003 Prentice Hall, Inc. All rights reserved.


38

17.5 Stacks

• Upcoming program
– Create stack from list
• insertAtFront, removeFromFront
– Software reusability
• Inheritance
– Stack inherits from List
• Composition
– Stack contains a private List object
– Performs operations on that object
– Makes stack implementation simple

 2003 Prentice Hall, Inc. All rights reserved.


39
1 // Fig. 17.10: stack.h
2 // Template Stack class definition derived from class List.
Outline
3 #ifndef STACK_H
4 #define STACK_H
Stack inherits from List. stack.h (1 of 2)
5
6 #include "list.h" // List class definition
7
8 template< class STACKTYPE >
9 class Stack : private List< STACKTYPE > {
10
11 public:
Define push and pop, which call
12 // push calls List function insertAtFront
13 void push( const STACKTYPE &data )
insertAtFront and
14 { removeFromFront.
15 insertAtFront( data );
16
17 } // end function push
18
19 // pop calls List function removeFromFront
20 bool pop( STACKTYPE &data )
21 {
22 return removeFromFront( data );
23
24 } // end function pop
25

 2003 Prentice Hall, Inc.


All rights reserved.
40
26 // isStackEmpty calls List function isEmpty
27 bool isStackEmpty() const
Outline
28 {
29 return isEmpty();
stack.h (2 of 2)
30
31 } // end function isStackEmpty
32
33 // printStack calls List function print
34 void printStack() const
35 {
36 print();
37
38 } // end function print
39
40 }; // end class Stack
41
42 #endif

 2003 Prentice Hall, Inc.


All rights reserved.
41
1 // Fig. 17.11: fig17_11.cpp
2 // Template Stack class test program.
Outline
3 #include <iostream>
4
fig17_11.cpp
5 using std::endl;
(1 of 3)
6
7 #include "stack.h" // Stack class definition
8
9 int main()
10 {
11 Stack< int > intStack; // create Stack of ints
12
13 cout << "processing an integer Stack" << endl;
14
15 // push integers onto intStack
16 for ( int i = 0; i < 4; i++ ) {
17 intStack.push( i );
18 intStack.printStack();
19
20 } // end for
21
22 // pop integers from intStack
23 int popInteger;
24

 2003 Prentice Hall, Inc.


All rights reserved.
42
25 while ( !intStack.isStackEmpty() ) {
26 intStack.pop( popInteger );
Outline
27 cout << popInteger << " popped from stack" << endl;
28 intStack.printStack();
fig17_11.cpp
29
(2 of 3)
30 } // end while
31
32 Stack< double > doubleStack; // create Stack of doubles
33 double value = 1.1;
34
35 cout << "processing a double Stack" << endl;
36
37 // push floating-point values onto doubleStack
38 for ( int j = 0; j< 4; j++ ) {
39 doubleStack.push( value );
40 doubleStack.printStack();
41 value += 1.1;
42
43 } // end for
44

 2003 Prentice Hall, Inc.


All rights reserved.
43
45 // pop floating-point values from doubleStack
46 double popDouble;
Outline
47
48 while ( !doubleStack.isStackEmpty() ) {
fig17_11.cpp
49 doubleStack.pop( popDouble );
(3 of 3)
50 cout << popDouble << " popped from stack" << endl;
51 doubleStack.printStack();
52
53 } // end while
54
55 return 0;
56
57 } // end main

 2003 Prentice Hall, Inc.


All rights reserved.
44
processing an integer Stack
The list is: 0
Outline
 
The list is: 1 0
fig17_11.cpp
 
output (1 of 2)
The list is: 2 1 0
 
The list is: 3 2 1 0
 
3 popped from stack
The list is: 2 1 0
 
2 popped from stack
The list is: 1 0
 
1 popped from stack
The list is: 0
 
0 popped from stack
The list is empty
 
processing a double Stack
The list is: 1.1
 
The list is: 2.2 1.1
 
The list is: 3.3 2.2 1.1

 2003 Prentice Hall, Inc.


All rights reserved.
45
The list is: 4.4 3.3 2.2 1.1
Outline
4.4 popped from stack
The list is: 3.3 2.2 1.1
fig17_11.cpp
 
output (2 of 2)
3.3 popped from stack
The list is: 2.2 1.1
 
2.2 popped from stack
The list is: 1.1
 
1.1 popped from stack
The list is empty
 
All nodes destroyed
 
All nodes destroyed

 2003 Prentice Hall, Inc.


All rights reserved.
46
1 // Fig. 17.12: stackcomposition.h
2 // Template Stack class definition with composed List object.
Outline
3 #ifndef STACKCOMPOSITION
4 #define STACKCOMPOSITION
stackcomposition.h
5
Alternative implementation of (1 of 2)
6 #include "list.h" // List class definition
7 stack.h, using
8 template< class STACKTYPE > composition.
9 class Stack {
10 Declare a private List
11 public: member, use to manipulate
12 stack.
// no constructor; List constructor does initialization
13
14 // push calls stackList object's insertAtFront function
15 void push( const STACKTYPE &data )
16 {
17 stackList.insertAtFront( data );
18
19 } // end function push
20
21 // pop calls stackList object's removeFromFront function
22 bool pop( STACKTYPE &data )
23 {
24 return stackList.removeFromFront( data );
25
26 } // end function pop
27

 2003 Prentice Hall, Inc.


All rights reserved.
47
28 // isStackEmpty calls stackList object's isEmpty function
29 bool isStackEmpty() const
Outline
30 {
31 return stackList.isEmpty();
stackcomposition.h
32
(2 of 2)
33 } // end function isStackEmpty
34
35 // printStack calls stackList object's print function
36 void printStack() const
37 {
38 stackList.print();
39
40 } // end function printStack
41
42 private:
43 List< STACKTYPE > stackList; // composed List object
44
45 }; // end class Stack
46
47 #endif

 2003 Prentice Hall, Inc.


All rights reserved.
48

17.6 Queues

• Queue
– Like waiting in line
– Nodes added to back (tail), removed from front (head)
– First-in, first-out (FIFO) data structure
– Insert/remove called enqueue/dequeue
• Applications
– Print spooling
• Documents wait in queue until printer available
– Packets on network
– File requests from server

 2003 Prentice Hall, Inc. All rights reserved.


49

17.6 Queues

• Upcoming program
– Queue implementation
– Reuse List as before
• insertAtBack (enqueue)
• removeFromFront (dequeue)

 2003 Prentice Hall, Inc. All rights reserved.


50
1 // Fig. 17.13: queue.h
2 // Template Queue class definition derived from class List.
Outline
3 #ifndef QUEUE_H
4 #define QUEUE_H
queue.h (1 of 2)
5
Inherit from template class
6 #include "list.h" // List class definition
7
List.
8 template< class QUEUETYPE >
9 class Queue : private List< QUEUETYPE > {
10
Reuse the appropriate List
11 public: functions.
12 // enqueue calls List function insertAtBack
13 void enqueue( const QUEUETYPE &data )
14 {
15 insertAtBack( data );
16
17 } // end function enqueue
18
19 // dequeue calls List function removeFromFront
20 bool dequeue( QUEUETYPE &data )
21 {
22 return removeFromFront( data );
23
24 } // end function dequeue
25

 2003 Prentice Hall, Inc.


All rights reserved.
51
26 // isQueueEmpty calls List function isEmpty
27 bool isQueueEmpty() const
Outline
28 {
29 return isEmpty();
queue.h (2 of 2)
30
31 } // end function isQueueEmpty
32
33 // printQueue calls List function print
34 void printQueue() const
35 {
36 print();
37
38 } // end function printQueue
39
40 }; // end class Queue
41
42 #endif

 2003 Prentice Hall, Inc.


All rights reserved.
52
1 // Fig. 17.14: fig17_14.cpp
2 // Template Queue class test program.
Outline
3 #include <iostream>
4
fig17_14.cpp
5 using std::endl;
(1 of 3)
6
7 #include "queue.h" // Queue class definition
8
9 int main()
10 {
11 Queue< int > intQueue; // create Queue of ints
12
13 cout << "processing an integer Queue" << endl;
14
15 // enqueue integers onto intQueue
16 for ( int i = 0; i < 4; i++ ) {
17 intQueue.enqueue( i );
18 intQueue.printQueue();
19
20 } // end for
21
22 // dequeue integers from intQueue
23 int dequeueInteger;
24

 2003 Prentice Hall, Inc.


All rights reserved.
53
25 while ( !intQueue.isQueueEmpty() ) {
26 intQueue.dequeue( dequeueInteger );
Outline
27 cout << dequeueInteger << " dequeued" << endl;
28 intQueue.printQueue();
fig17_14.cpp
29
(2 of 3)
30 } // end while
31
32 Queue< double > doubleQueue; // create Queue of doubles
33 double value = 1.1;
34
35 cout << "processing a double Queue" << endl;
36
37 // enqueue floating-point values onto doubleQueue
38 for ( int j = 0; j< 4; j++ ) {
39 doubleQueue.enqueue( value );
40 doubleQueue.printQueue();
41 value += 1.1;
42
43 } // end for
44

 2003 Prentice Hall, Inc.


All rights reserved.
54
45 // dequeue floating-point values from doubleQueue
46 double dequeueDouble;
Outline
47
48 while ( !doubleQueue.isQueueEmpty() ) {
fig17_14.cpp
49 doubleQueue.dequeue( dequeueDouble );
(3 of 3)
50 cout << dequeueDouble << " dequeued" << endl;
51 doubleQueue.printQueue();
52
53 } // end while
54
55 return 0;
56
57 } // end main

 2003 Prentice Hall, Inc.


All rights reserved.
55
processing an integer Queue
The list is: 0
Outline
 
The list is: 0 1
fig17_14.cpp
 
output (1 of 2)
The list is: 0 1 2
 
The list is: 0 1 2 3
 
0 dequeued
The list is: 1 2 3
 
1 dequeued
The list is: 2 3
 
2 dequeued
The list is: 3
 
3 dequeued
The list is empty
 
processing a double Queue
The list is: 1.1
 
The list is: 1.1 2.2

 2003 Prentice Hall, Inc.


All rights reserved.
56
The list is: 1.1 2.2 3.3
 
Outline
The list is: 1.1 2.2 3.3 4.4
 
fig17_14.cpp
1.1 dequeued
output (2 of 2)
The list is: 2.2 3.3 4.4
 
2.2 dequeued
The list is: 3.3 4.4
 
3.3 dequeued
The list is: 4.4

4.4 dequeued
The list is empty
 
All nodes destroyed
 
All nodes destroyed

 2003 Prentice Hall, Inc.


All rights reserved.
57

17.7 Trees

• Linear data structures


– Lists, queues, stacks
• Trees
– Nonlinear, two-dimensional
– Tree nodes have 2 or more links
– Binary trees have exactly 2 links/node
• None, both, or one link can be null

 2003 Prentice Hall, Inc. All rights reserved.


58

17.7 Trees

• Terminology
– Root node: first node on tree
– Link refers to child of node
• Left child is root of left subtree
• Right child is root of right subtree
– Leaf node: node with no children
– Trees drawn from root downwards

A D

 2003 Prentice Hall, Inc. All rights reserved.


59

17.7 Trees

• Binary search tree


– Values in left subtree less than parent node
– Values in right subtree greater than parent
• Does not allow duplicate values (good way to remove them)
– Fast searches, log2n comparisons for a balanced tree

47

25 77
11 43 65 93
7 17 31 44 68

 2003 Prentice Hall, Inc. All rights reserved.


60

17.7 Trees

• Inserting nodes
– Use recursive function
– Begin at root
– If current node empty, insert new node here (base case)
– Otherwise,
• If value > node, insert into right subtree
• If value < node, insert into left subtree
• If neither > nor <, must be =
– Ignore duplicate

 2003 Prentice Hall, Inc. All rights reserved.


61

17.7 Trees

• Tree traversals
– In-order (print tree values from least to greatest)
• Traverse left subtree (call function again)
• Print node
• Traverse right subtree
– Preorder
• Print node
• Traverse left subtree
• Traverse right subtree
– Postorder
• Traverse left subtree
• Traverse rigth subtree
• Print node

 2003 Prentice Hall, Inc. All rights reserved.


62

17.7 Trees

• Upcoming program
– Create 2 template classes
– TreeNode
• data
• leftPtr
• rightPtr
– Tree
• rootPtr
• Functions
– InsertNode
– inOrderTraversal
– preOrderTraversal
– postOrderTraversal

 2003 Prentice Hall, Inc. All rights reserved.


63
1 // Fig. 17.17: treenode.h
2 // Template TreeNode class definition.
Outline
3 #ifndef TREENODE_H
4 #define TREENODE_H
treenode.h (1 of 2)
5
6 // forward declaration of class Tree
7 template< class NODETYPE > class Tree;
8
9 template< class NODETYPE >
10 class TreeNode {
11 friend class Tree< NODETYPE >;
12
13 public:
14 Binary trees have two
15 // constructor pointers.
16 TreeNode( const NODETYPE &d )
17 : leftPtr( 0 ),
18 data( d ),
19 rightPtr( 0 )
20 {
21 // empty body
22
23 } // end TreeNode constructor
24

 2003 Prentice Hall, Inc.


All rights reserved.
64
25 // return copy of node's data
26 NODETYPE getData() const
Outline
27 {
28 return data;
treenode.h (2 of 2)
29
30 } // end getData function
31
32 private:
33 TreeNode< NODETYPE > *leftPtr; // pointer to left subtree
34 NODETYPE data;
35 TreeNode< NODETYPE > *rightPtr; // pointer to right subtree
36
37 }; // end class TreeNode
38
39 #endif

 2003 Prentice Hall, Inc.


All rights reserved.
65
1 // Fig. 17.18: tree.h
2 // Template Tree class definition.
Outline
3 #ifndef TREE_H
4 #define TREE_H
tree.h (1 of 6)
5
6 #include <iostream>
7
8 using std::endl;
9
10 #include <new>
11 #include "treenode.h"
12
13 template< class NODETYPE >
14 class Tree {
15
16 public:
17 Tree();
18 void insertNode( const NODETYPE & );
19 void preOrderTraversal() const;
20 void inOrderTraversal() const;
21 void postOrderTraversal() const;
22
23 private:
24 TreeNode< NODETYPE > *rootPtr;
25

 2003 Prentice Hall, Inc.


All rights reserved.
66
26 // utility functions
27 void insertNodeHelper(
Outline
28 TreeNode< NODETYPE > **, const NODETYPE & );
29 void preOrderHelper( TreeNode< NODETYPE > * ) const;
tree.h (2 of 6)
30 void inOrderHelper( TreeNode< NODETYPE > * ) const;
31 void postOrderHelper( TreeNode< NODETYPE > * ) const;
32
33 }; // end class Tree
34
35 // constructor
36 template< class NODETYPE >
37 Tree< NODETYPE >::Tree()
38 {
39 rootPtr = 0;
40
41 } // end Tree constructor
42
43 // insert node in Tree
44 template< class NODETYPE >
45 void Tree< NODETYPE >::insertNode( const NODETYPE &value )
46 {
47 insertNodeHelper( &rootPtr, value );
48
49 } // end function insertNode
50

 2003 Prentice Hall, Inc.


All rights reserved.
67
51 // utility function called by insertNode; receives a pointer
52 // to a pointer so that the function can modify pointer's value
Outline
53 template< class NODETYPE >
54 void Tree< NODETYPE >::insertNodeHelper(
tree.h (3 of 6)
55 TreeNode< NODETYPE > **ptr, const NODETYPE &value )
Recursive function to insert a
56 {
57 // subtree is empty; create new TreeNode containing value
new node. If the current node
58 if ( *ptr == 0 ) is empty, insert the new node
59 *ptr = new TreeNode< NODETYPE >( value ); here.
60
61 else // subtree is not empty If new value greater than
62 current node (ptr), insert
63 // data to insert is less than data in current node into right subtree.
64 if ( value < ( *ptr )->data )
65 insertNodeHelper( &( ( *ptr )->leftPtr ), value );
If less, insert into left subtree.
66
67 else
68
If neither case applies, node is
69 // data to insert is greater than data in current node a duplicate -- ignore.
70 if ( value > ( *ptr )->data )
71 insertNodeHelper( &( ( *ptr )->rightPtr ), value );
72
73 else // duplicate data value ignored
74 cout << value << " dup" << endl;
75
76 } // end function insertNodeHelper

 2003 Prentice Hall, Inc.


All rights reserved.
68
77
78 // begin preorder traversal of Tree
Outline
79 template< class NODETYPE >
80 void Tree< NODETYPE >::preOrderTraversal() const
tree.h (4 of 6)
81 {
82 preOrderHelper( rootPtr );
83
84 } // end function preOrderTraversal
85
86 // utility function to perform preorder traversal of Tree
87 template< class NODETYPE >
88 void Tree< NODETYPE >::preOrderHelper(
Preorder: print, left, right
89 TreeNode< NODETYPE > *ptr ) const
90 {
91 if ( ptr != 0 ) {
92 cout << ptr->data << ' '; // process node
93 preOrderHelper( ptr->leftPtr ); // go to left subtree
94 preOrderHelper( ptr->rightPtr ); // go to right subtree
95
96 } // end if
97
98 } // end function preOrderHelper
99

 2003 Prentice Hall, Inc.


All rights reserved.
69
100 // begin inorder traversal of Tree
101 template< class NODETYPE >
Outline
102 void Tree< NODETYPE >::inOrderTraversal() const
103 {
tree.h (5 of 6)
104 inOrderHelper( rootPtr );
105
106 } // end function inOrderTraversal
107
108 // utility function to perform inorder traversal of Tree
109 template< class NODETYPE >
110 void Tree< NODETYPE >::inOrderHelper( In order: left, print, right
111 TreeNode< NODETYPE > *ptr ) const
112 {
113 if ( ptr != 0 ) {
114 inOrderHelper( ptr->leftPtr ); // go to left subtree
115 cout << ptr->data << ' '; // process node
116 inOrderHelper( ptr->rightPtr ); // go to right subtree
117
118 } // end if
119
120 } // end function inOrderHelper
121

 2003 Prentice Hall, Inc.


All rights reserved.
70
122 // begin postorder traversal of Tree
123 template< class NODETYPE >
Outline
124 void Tree< NODETYPE >::postOrderTraversal() const
125 {
tree.h (6 of 6)
126 postOrderHelper( rootPtr );
127
128 } // end function postOrderTraversal
129
130 // utility function to perform postorder traversal of Tree
131 template< class NODETYPE >
132 void Tree< NODETYPE >::postOrderHelper( Postorder: left, right, print
133 TreeNode< NODETYPE > *ptr ) const
134 {
135 if ( ptr != 0 ) {
136 postOrderHelper( ptr->leftPtr ); // go to left subtree
137 postOrderHelper( ptr->rightPtr ); // go to right subtree
138 cout << ptr->data << ' '; // process node
139
140 } // end if
141
142 } // end function postOrderHelper
143
144 #endif

 2003 Prentice Hall, Inc.


All rights reserved.
71
1 // Fig. 17.19: fig17_19.cpp
2 // Tree class test program.
Outline
3 #include <iostream>
4
fig17_19.cpp
5 using std::cout;
(1 of 3)
6 using std::cin;
7 using std::fixed;
8
9 #include <iomanip>
10 using std::setprecision;
11
12 #include "tree.h" // Tree class definition
13
14 int main()
15 {
16 Tree< int > intTree; // create Tree of int values
17 int intValue;
18
19 cout << "Enter 10 integer values:\n";
20
21 for( int i = 0; i < 10; i++ ) {
22 cin >> intValue;
23 intTree.insertNode( intValue );
24
25 } // end for

 2003 Prentice Hall, Inc.


All rights reserved.
72
26
27 cout << "\nPreorder traversal\n";
Outline
28 intTree.preOrderTraversal();
29
fig17_19.cpp
30 cout << "\nInorder traversal\n";
(2 of 3)
31 intTree.inOrderTraversal();
32
33 cout << "\nPostorder traversal\n";
34 intTree.postOrderTraversal();
35
36 Tree< double > doubleTree; // create Tree of double values
37 double doubleValue;
38
39 cout << fixed << setprecision( 1 )
40 << "\n\n\nEnter 10 double values:\n";
41
42 for ( int j = 0; j < 10; j++ ) {
43 cin >> doubleValue;
44 doubleTree.insertNode( doubleValue );
45
46 } // end for
47
48 cout << "\nPreorder traversal\n";
49 doubleTree.preOrderTraversal();
50

 2003 Prentice Hall, Inc.


All rights reserved.
73
51 cout << "\nInorder traversal\n";
52 doubleTree.inOrderTraversal();
Outline
53
54 cout << "\nPostorder traversal\n";
fig17_19.cpp
55 doubleTree.postOrderTraversal();
(3 of 3)
56
57 cout << endl;
58
59 return 0;
60
61 } // end main

 2003 Prentice Hall, Inc.


All rights reserved.
74
Enter 10 integer values:
50 25 75 12 33 67 88 6 13 68
Outline
 
Preorder traversal
fig17_19.cpp
50 25 12 6 13 33 75 67 68 88
output (1 of 1)
Inorder traversal
6 12 13 25 33 50 67 68 75 88
Postorder traversal
6 13 12 33 25 68 67 88 75 50
 
 
Enter 10 double values:
39.2 16.5 82.7 3.3 65.2 90.8 1.1 4.4 89.5 92.5
 
Preorder traversal
39.2 16.5 3.3 1.1 4.4 82.7 65.2 90.8 89.5 92.5
Inorder traversal
1.1 3.3 4.4 16.5 39.2 65.2 82.7 89.5 90.8 92.5
Postorder traversal
1.1 4.4 3.3 16.5 65.2 89.5 92.5 90.8 82.7 39.2

 2003 Prentice Hall, Inc.


All rights reserved.

You might also like