Download presentation
Presentation is loading. Please wait.
1
CH3. STACKS AND QUEUES
2
3.1 Templates in C++ Make classes and functions more reusable 5/9/2019
3
3.1 Templates in C++(Cont’)
3.1.1 Templates Functions Without using templates 1 (example) 2 void sort(int *a, const int n) 3 // sort the n integers a[0] to a[n-1] into non-decreasing order 4 { for (int i = 0; i < n; i++) { int j = i; // find smallest integer in a[i] to a[n-1] for (int k = i + 1; k < n; k++) if (a[k] < a[j]) j = k ; // interchange int temp = a[i]; a[i] = a[j]; a[j] = temp; } 14 } Program 1.6 : Selection sort 5/9/2019
4
3.1 Templates in C++(Cont’)
to sort an array of floating point numbers In line 1, int *a → float *a In line 2, integers → floats In line 11, int → float this process repeats for arrays of other data types the concept of overloaded function Template (parameterized type) variable that can be instantiated to any data type 5/9/2019
5
3.1 Templates in C++(Cont’)
template <class KeyType> void sort(KeyType *a, int n) // sort the n KeyTypes a[0] to a[n-1] into non-decreasing order { for( int i=0; i<n; i++) int j = i; // find smallest KeyType in a[i] to a[n-1] for( int k = i+1; k<n; k++) if( a[k] < a[j]) j = k; // interchange KeyType temp = a[i]; a[i] = a[j]; a[j] = temp; } Program 3.1 : Selection sort using templates 5/9/2019
6
3.1 Templates in C++(Cont’)
float farray[100]; int intarray[250]; ... // assume that the arrays are initialized at this point sort(farray, 100); sort(intarray, 250); Program 3.2 : Code fragment illustrating template instantiation 5/9/2019
7
3.1 Templates in C++(Cont’)
Copy constructor invoked when an object is initialized with another object a type specifier that specifies the type of the left hand side object in an initialization Operators in functions using templates Operators "<", "=", copy constructor automatically defined for int and float not pre-defined for user-defined data types may be overloaded in a manner that is consistent with their usages if = and copy constructor for a user-defined class are not defined by the user, the compiler creates default implementations 5/9/2019
8
3.1 Templates in C++(Cont’)
3.1.2 Using Templates to Represent Container Class Container class a data structure that stores a number of data objects objects can be added or deleted Bag can have multiple occurrences of the same object the position of an element is immaterial any element can be removed for a delete operation C++ array implementation of Bag of integers insertion : to the first available position deletion : the element in the middle position and then compact upper half of array 5/9/2019
9
3.1 Templates in C++(Cont’)
class Bag { public: Bag (int MaxSize = DefaultSize); // constructor ~Bag(); // destructor void Add(int); // insert an integer into bag int *Delete(int&); // delete an integer from bag Boolean IsFull(); // return TRUE if the bag is full; FALSE otherwise Boolean IsEmpty(); // return TRUE if the bag is empty; FALSE otherwise private: void Full(); // action when bag is full void Empty(); // action when bag is empty int *array; int MaxSize; // size of array int top; // highest position in array that contains an element } Program 3.3 : Definition of class Bag containing integers 5/9/2019
10
3.1 Templates in C++(Cont’)
Implementation of Bag operations Bag::Bag (int MaxBagSize): MaxSize (MaxBagSize) //Maxsize = MaxBagSize; array = new int[MaxSize]; top = -1; Bag::~Bag() delete [ ] array; inline Boolean Bag::IsFull() { if (top == MaxSize-1) return TRUE; else return FALSE; } inline Boolean Bag::IsEmpty() if (top == -1) return TRUE; else return FALSE; inline void Bag::Full() cerr << "Data structure is full" << endl; 5/9/2019
11
3.1 Templates in C++(Cont’)
inline void Bag::Empty() { cerr << "Data structure is empty" << endl; } void Bag::Add(int x) if( IsFull() ) Full(); else array[++top] = x; int* Bag::Delete(int& x) if( IsEmpty() ) { Empty(); return 0; } int deletePos = top/2; x = array[deletePos]; for ( int index = deletePos; index<top; index++) array[index] = array[index+1]; //compact upper half of array top--; return &x; Program 3.4 : Implementation of operations on Bag 5/9/2019
12
3.1 Templates in C++(Cont’)
Template class definition for Bag template <class Type> class Bag { public: Bag (int MaxSize = DefaultSize); // constructor ~Bag(); // destructor void Add(const Type&); // insert element into bag Type *Delete(Type&); // delete element from bag Boolean IsFull(); // return TRUE if the bag is full; FALSE otherwise Boolean IsEmpty(); // return TRUE if the bag is empty; FALSE otherwise private: void Full(); // action when bag is full void Empty(); // action when bag is empty Type *array; int MaxSize; // size of array int top; // highest position in array that contains an element } Program 3.5 : Definition of template class Bag 5/9/2019
13
3.1 Templates in C++(Cont’)
Instantiation of template class Bag Bag<int>a ; Bag<Rectangle>r ; Implementation of operations of template class Bag template <class Type> Bag<Type>::Bag (int MaxBagSize): MaxSize (MaxBagSize) { array = new Type[MaxSize]; top = -1; } Bag<Type>::~Bag() delete [] array; 5/9/2019
14
3.1 Templates in C++(Cont’)
template <class Type> void Bag<Type>::Add(const Type& x) { if( IsFull()) Full(); else array[++top] = x; } Type* Bag<Type>::Delete(Type& x) if( IsEmpty()) { Empty(); return 0; int deletePos = top/2; x = array[deletePos]; for ( int index = deletePos; index<top; index++) array[index] = array[index+1]; //compact upper half of array top--; return &x; Program 3.6 : Implementation of operations on Bag 5/9/2019
15
3.2 Stack Abstract Data Type
an ordered list in which insertions and deletions are made at one end called the top S=(a0, ..., an-1) a0 : bottom element an-1 : top element ai is on top of ai-1, 0<i<n Last-In-First-Out(LIFO) list 5/9/2019
16
3.2 Stack Abstract Data Type(Cont’)
Add A, B, C, D, E, then delete E E top D top D D top C top C C C B top B B B B A top A A A A A add add add add del Figure 3.1 : Inserting and deleting elements in a stack 5/9/2019
17
3.2 Stack Abstract Data Type(Cont’)
System stack used by a program at run time to process function calls when a function is invoked, the program creates a stack frame, and places it on top of the system stack previous frame pointer return address local variables parameters when a function terminates, its stack frame is removed a recursive call is processed in the same way a main function invokes function a1 (a) : before a1 is invoked (b) : after a1 has been invoked fp : current stack frame pointer 5/9/2019
18
3.2 Stack Abstract Data Type(Cont’)
previous frame pointer fp return address a1 local variables previous frame pointer previous frame pointer fp return address main return address main (a) (b) Figure 3.2 : System stack after function call 5/9/2019
19
3.2 Stack Abstract Data Type(Cont’)
Program Code 외부 data, Static data malloc, class형 data local var (static data, 외부data) Text Heap Stack Figure : 기억장소 5/9/2019
20
3.2 Stack Abstract Data Type(Cont’)
dynamic 기억장소 text 기억장소 196 y=4; 레지스터 goto function a1 (300) 200 PC 200 204 FP 1000 …. local variable y=4 300 function a1 main frame 1000 previous FP 304 x=5; return address 5/9/2019
21
3.2 Stack Abstract Data Type(Cont’)
dynamic 기억장소 text 기억장소 196 y=4; local variable x=5 레지스터 goto function a1 (300) a1 200 PC 300 960 FP 1000 204 return add (204) FP 960 …. local variable y=4 300 function a1 main frame 1000 previous FP 304 x=5; return address Figure : Function call a1( ), FP (frame pointer), PC (program counter) 5/9/2019
22
3.2 Stack Abstract Data Type(Cont’)
Stack ADT template <class KeyType> class Stack { // objects: A finite ordered list with zero or more elements. public: Stack (int MaxStackSize = DefaultSize); // Create an empty stack whose maximum size is MaxStackSize Boolean IsFull(); // if number of elements in the stack is equal to the // maximum size of the stack, return TRUE (1); otherwise, // return FALSE (0) 5/9/2019
23
3.2 Stack Abstract Data Type(Cont’)
void Add(const KeyType& item); // if IsFull(), then StackFull(); else insert item into the top of the stack. Boolean IsEmpty(); // if number of elements in the stack is 0, return TRUE (1) // else return FALSE (0). KeyType* Delete(KeyType&); // if IsEmpty(), then StackEmpty() and return 0; // else remove and return a pointer to the top element of the stack. }; ADT 3.1 : Abstract data type Stack 5/9/2019
24
3.2 Stack Abstract Data Type(Cont’)
Implementation of stack ADT use an one-dim array stack[MaxSize] bottom element is stored in stack[0] top points to the top element initially, top=-1 for an empty stack data member declarations in class template < class KeyType > class stack private: int top; KeyType *stack; int MaxSize; public: ...... 5/9/2019
25
3.2 Stack Abstract Data Type(Cont’)
constructor definition member function IsFull() template <class KeyType> Stack<KeyType>::Stack (int MaxStackSize): MaxSize (MaxStackSize) { stack = new KeyType[MaxSize]; top = -1; } template <class KeyType> inline Boolean Stack<KeyType>::IsFull() { if (top == MaxSize-1) return TRUE; else return FALSE; } 5/9/2019
26
3.2 Stack Abstract Data Type(Cont’)
member function IsEmpty() Add operation template <class KeyType> inline Boolean Stack<KeyType>::IsEmpty() { if (top == -1) return TRUE; else return FALSE; } template <class KeyType> void Stack<KeyType>::Add(const KeyType& x) // add x to stack { if (IsFull()) StackFull(); else stack[++top] = x; } Program 3.7 : Adding to a stack 5/9/2019
27
3.2 Stack Abstract Data Type(Cont’)
Delete operation StackFull() and StackEmpty() depend on the particular application template <class KeyType> KeyType* Stack<KeyType>::Delete(KeyType& x) // Remove top element from stack. if (IsEmpty()) StackEmpty(); return 0; x = stack[top--]; return &x; Program 3.8 : Deleting from a stack 5/9/2019
28
3.3 Queue Abstract Data Type
can ordered list in which all insertions take place at one end and all deletions take place at the opposite end Q=(a0, a1, ..., an-1) a0 : front element an-1 : rear element ai is behind ai-1, 0<i<n First-In-First-Out(FIFO) list 5/9/2019
29
3.3 Queue Abstract Data Type(Cont’)
Inserting A, B, C, D, E, then delete an element A A B A B C A B C D A B C D E B C D E f r f r f r f r f r add delete f = queue front r = queue rear Figure 3.4 : Inserting and deleting elements in a queue 5/9/2019
30
3.3 Queue Abstract Data Type(Cont’)
Queue ADT template <class KeyType> class Queue // objects: A finite ordered list with zero or more elements. public: Queue (int MaxQueueSize = DefaultSize); // Create an empty queue whose maximum size is MaxQueueSize Boolean IsFull(); // if number of elements in the queue is equal to the // maximum size of the queue, ruturn TRUE (1); // otherwise, return FALSE (0) 5/9/2019
31
3.3 Queue Abstract Data Type(Cont’)
void Add(const KeyType& item); // if IsFull(), then QueueFull(); else insert item at rear of // the queue. Boolean IsEmpty(); // if number of elements in the queue is equal to 0, // return TRUE (1) else return FALSE (0) KeyType* Delete(KeyType&); // if IsEmpty(), then QueueEmpty() and return 0; // else remove the item at the front of the queue and // return a pointer to it. ADT 3.2 : Abstract data type Queue 5/9/2019
32
3.3 Queue Abstract Data Type(Cont’)
Implementation of Queue ADT use an one-dim array two variables front : one less than the position of the first element rear : the position of the last element data member declaration in class templates < class KeyType > class Queue private: int front, rear; keyType *queue; int MaxSize; public: ...... 5/9/2019
33
3.3 Queue Abstract Data Type(Cont’)
constructor definition member function IsFull() IsFull() does not exactly correspond to ADT 3.2 if rear=MaxSize-1 and front>-1, Queue is not full template <class KeyType> Queue<KeyType>::Queue (int MaxQueueSize): MaxSize (MaxQueueSize) { queue = new KeyType[MaxSize]; front = rear = -1; } template <class KeyType> inline Boolean Queue<KeyType>::IsFull() { if (rear == MaxSize-1) return TRUE; else return FALSE; } 5/9/2019
34
3.3 Queue Abstract Data Type(Cont’)
member function IsEmpty() template <class KeyType> inline Boolean Queue<KeyType>::IsEmpty() { if (front == rear) return TRUE; else return FALSE; } 5/9/2019
35
3.3 Queue Abstract Data Type(Cont’)
Add function template <class KeyType> void Queue<KeyType>::Add(const KeyType& x) // add x to the queue { if (IsFull()) QueueFull(); else queue[++rear] = x; } Program 3.9 : Adding to a queue 5/9/2019
36
3.3 Queue Abstract Data Type(Cont’)
Delete function template <class KeyType> KeyType* Queue<KeyType>::Delete(KeyType& x) // Remove front element from queue. { if (IsEmpty()) QueueEmpty(); return 0; x = queue[++front]; return &x; } Program 3.10 : Deleting from a queue 5/9/2019
37
3.3 Queue Abstract Data Type(Cont’)
Job Scheduling Sequential queue the sequential representation of a queue has pitfalls a job queue by an operating system front rear Q[0] [1] [2] [3] [4] [5] [6] …. Comments -1 1 2 3 queue empty J1 J J2 J J2 J3 J2 J3 J2 J3 J4 J3 J4 intial jop 1 joins Q jop 2 joins Q jop 3 joins Q jop 1 leaves Q jop 4 joins Q jop 2 leaves Q Figure 3.5 : Insertion and deletion from a queue 5/9/2019
38
3.3 Queue Abstract Data Type(Cont’)
as jobs enter and leave the system, the queue gradually shifts to the right eventually rear=MaxSize-1 the queue is full QueueFull() should move the entire queue to the left first element at queue[0] front=-1 recalculate rear worst-time complexity is O (MaxSize) worst case alternate requests to delete and add elements 5/9/2019
39
3.3 Queue Abstract Data Type(Cont’)
front rear q[0] [1] [2] … [n-1] Comments -1 n – 1 J J2 J3 … Jn J2 J3 … Jn J J3 J4 … Jn + 1 J3 J4 … Jn + 1 J J4 J5 … Jn + 2 initial state delete J1 add Jn + 1 (jobs J2 through Jn are moved) delete J2 add Jn + 2 Figure 3.6 : Queue example 5/9/2019
40
3.3 Queue Abstract Data Type(Cont’)
Circular queue the array queue[MaxSize] as circular when rear==MaxSize-1, the next element is entered at q[0] if it is empty front : point one position counterclockwise from the first element a maximum of MaxSize-1 rather than MaxSize to determine whether the queue is full or empty Empty if front == rear Full if front == rear + 1 Initially front == rear == 0 5/9/2019
41
3.3 Queue Abstract Data Type(Cont’)
[4] [4] J4 [n-4] [n-4] J3 [3] [3] J1 [n-3] [n-3] J2 [2] J2 [2] J1 [n-2] J4 J3 [n-2] [1] [1] [n-1] [n-1] [0] [0] front = n - 4; rear = 0 front = 0; rear = 4 Figure 3.7 : Circular queue of MaxSize=n elements and four- jobs : J1, J2, J3, J4 5/9/2019
42
3.3 Queue Abstract Data Type(Cont’)
add an element circular shift of rear (move one position clockwise) if newrear==front, queue is full if(rear==MaxSize-1) newrear=0; else newrear=rear+1; template <class KeyType> void Queue<KeyType>::Add(const KeyType& x) // add x to the circular queue { int k = (rear+1) % MaxSize; if (front == k) QueueFull(); else queue[rear=k] = x; } Program 3.11 : Adding to a circular queue 5/9/2019
43
3.3 Queue Abstract Data Type(Cont’)
delete an element if front==rear, queue is empty circular shift of front (move one position clockwise) template <class KeyType> KeyType* Queue<KeyType>::Delete(KeyType& x) // remove front element from queue { if (front == rear) { QueueEmpty(); return 0;} x = queue[++front %= MaxSize]; return &x; } Program 3.12 : Deleting from a circular queue 5/9/2019
44
3.4 Subtyping and Inheritance in C++
subtype relationships between ADTs IS-A relationship B IS-A A B is more specialized than A A is more general than B Objects of Type A Objects of Type B 5/9/2019
45
3.4 Subtyping and Inheritance in C++(Cont’)
Examples Chair IS-A Furniture Lion IS-A Mammal Stack IS-A Bag 5/9/2019
46
3.4 Subtyping and Inheritance in C++(Cont’)
C++ mechanism public inheritance base class : more general ADT derived class : more specialized ADT the derived class inherits all the non-private (protected or public) members (data and functions) of the base class inherited members have the same level of access in the derived class as they did in the base class Reuse interface : inherited member functions have the same prototypes implementation : only functions to override the base class implementation are reimplemented 5/9/2019
47
3.4 Subtyping and Inheritance in C++(Cont’)
class Bag { public: Bag (int MaxSize = DefaultSize); // constructor virtual ~Bag(); // destructor // virtual function can be defined in derived class // refer the section 4.11 virtual void Add(int); // insert element into bag virtual int *Delete(int&); // delete element from bag virtual Boolean IsFull(); // return TRUE if the bag is full; // FALSE otherwise virtual Boolean IsEmpty(); //return TRUE if the bag is empty; protected: virtual void Full(); // action when bag is full virtual void Empty(); // action when bag is empty 5/9/2019
48
3.4 Subtyping and Inheritance in C++(Cont’)
int *array; int MaxSize; // size of array int top; // highest position in array that contains an element }; class Stack: public Bag { public: Stack (int MaxSize = DefaultSize); // constructor ~Stack(); // destructor int *Delete(int&); // delete element from stack Program 3.13 : Definition of Bag and Stack. 5/9/2019
49
3.4 Subtyping and Inheritance in C++(Cont’)
Stack::Stack (int MaxStackSize): Bag(MaxStackSize) { } // Constructor for Stack calls constructor for Bag. Stack::~Stack() { } // Destructor for Bag is automatically called when Stack is // destroyed. This ensures that array is deleted. int *Stack::Delete(int& x) { if (IsEmpty()) {Empty(); return 0;} x = array[top--]; return &x; } Program 3.14 : Implementation of Stack operations 5/9/2019
50
3.4 Subtyping and Inheritance in C++(Cont’)
Example Bag b(3); //uses Bag constructor to create array of size 3 Stack s(3); //uses Stack constructor to create array of size 3 b.Add(1); b.Add(2); b.Add(3); //use Bag::Add. //Bag::Add calls functions Bag::IsFull and Bag::Full s.Add(1); s.Add(2); s.Add(3); //Stack::Add not defined, so use Bag::Add. Bag::Add calls //Bag::IsFull and Bag::Full because these have not been //redefined in Stack 5/9/2019
51
3.4 Subtyping and Inheritance in C++(Cont’)
int x; b.Delete(x); //uses Bag::Delete, which calls Bag::IsEmpty and //Bag::Empty s.Delete(x); //uses Stack::Delete, which calls Bag::IsEmpty and //Bag::Empty because these have not been redefined in //Stack. result : b=<1, 3>, s=<1, 2> Queue subtype of Bag elements are deleted in FIFO order 5/9/2019
52
3.5 A Mazing Problem Maze represent by a two-dim array,
maze[i][j], where 1≤i≤m and 1≤j≤p 1 means a blocked path 0 means a path starts at maze[1][1] exits at maze[m][p] 5/9/2019
53
3.5 A Mazing Problem(Cont’)
entrance exit Figure 3.8 : An example maze 5/9/2019
54
3.5 A Mazing Problem(Cont’)
Possible moves from X=maze[i][j] NW N NE [i-1][j-1] [i-1][j] [i-1][j+1] W [i][j-1] X [i][j+1] E [i][j] [i+1][j-1] [i+1][j] [i+1][j+1] SW S SE Figure 3.9 Allowable moves 5/9/2019
55
3.5 A Mazing Problem(Cont’)
To avoid checking for border conditions surround the maze by a border of ones declare the array as maze[m+2][p+2] Table to predefine the possible directions to move necessary data types enum directions {N, NE, E, SE, S, SW, W, NW}; offsets move[8]; struct offsets { int a, b; }; 5/9/2019
56
3.5 A Mazing Problem(Cont’)
q move [q].a move[q].b N – NE – E SE S SW –1 W –1 NW – –1 Figure 3.10 : Table of moves to find maze[g][h] that is SW of maze[i][j] g=i+move[SW].a h=j+move[SW].b 5/9/2019
57
3.5 A Mazing Problem(Cont’)
mark[m+2][p+2] to prevent from going down the same path twice initialize stack to the maze entrance coordinates and direction east; while (stack is not empty) { (i, j, dir) = coordinates and direction deleted from top of stack ; while (there are more moves) (g, h) = coordinates of next move ; if ((g == m) && (h == p)) success ; if (!maze[g][h] // legal move && !mark[g][h]) // haven't been here before 5/9/2019
58
3.5 A Mazing Problem(Cont’)
{ mark[g][h] = 1; dir = next direction to try ; (i, j, dir) to top of stack ; i =g; j = h; dir = north; } cout << "No path found" << endl; Program 3.15 : First pass at finding a path through a maze 5/9/2019
59
3.5 A Mazing Problem(Cont’)
Maze algorithm arrays maze, mark, move are global Stack is a stack of items struct items { int x, y, dir; }; the computing time is O(mp) 5/9/2019
60
3.5 A Mazing Problem(Cont’)
entrance exit Figure 3.11 : A maze with a long path 5/9/2019
61
3.5 A Mazing Problem(Cont’)
void path(int m, int p) // Output a path (if any) in the maze ; maze[0][i] = maze[m+1][i] // = maze[j][0] = maze[j][p+1] = 1, 0≤i≤p+1, 0≤j≤m+1. { // start at (1, 1) mark[1][1]=1; stack<items> stack(m*p); items temp; temp.x = 1; temp.y = 1; temp.dir = E; stack.Add(temp); while (!stack.IsEmpty()) // stack not empty temp = *stack.Delete(temp); // unstack int i = temp.x; int j = temp.y; int d = temp.dir; 5/9/2019
62
3.5 A Mazing Problem(Cont’)
while (d < 8) // move forward { int g = i + move[d].a; int h = j + move[d].b; if ((g == m) && (h == p)) { // reached exit // output path cout << stack; cout << i << " " << j << endl; // last two squares on the path cout << m << " " << p << endl; return; } if ((!maze[g][h]) && (!mark[g][h])) { // new position mark[g][h] = 1; 5/9/2019
63
3.5 A Mazing Problem(Cont’)
temp.x = i; temp.y = j; temp.dir = d+1; stack.Add(temp); // stack it i = g; j = h; d = N; // move to (g, h) } else d++; // try next direction cout << "no path in maze" << endl; Program 3.16 : Finding a path through a maze 5/9/2019
64
3.5 A Mazing Problem(Cont’)
template <class KeyType> ostream& operator <<(ostream& os, Stact<Keyype>& s) { os << “top = “ << s.top<< endl; for (int i=0; i<=s.top; i++) os << i<< “:” << s.stact[i] << endl; return os; } ostream& operator <<(ostream& os, items& item) return os <<item.x <<“,” << item.y <<“,” <<item.dir; } Program 3.17: Overloading operator << 5/9/2019
65
3.6 Evaluation of Expressions
Operators arithmetic operators basic : +, -, *, / other : unary minus, % relational operators <, <=, ==, <>, >=, > logical operators : &&, ||, ! Precedence Figure 3.12 : Priority of operators in C++ Priority Operator 1 unary minus, ! 2 *, /,% 3 +, - 4 <. <=, >=, > 5 ==, != 6 && 7 || 5/9/2019
66
3.6 Evaluation of Expressions(Cont’)
Postfix Notation Notations Infix notation : A*B/C Postfix notation : AB*C/ Prefix notation : /*ABC Example Infix : A/B-C+D*E-A*C =(((A/B-C)+(D*E))-(A*C) Postfix : AB/C-DE*+AC*- operations postfix T1 = A / B T1 C - D E * + A C * - T2 = T1 - C T2 D E * + A C *- T3 = D * E T2 T3 + A C * - T4 = T2 + T T4 A C *- T5 = A * C T4 T5 - T6 = T4 - T T6 Figure 3.13 : Postfix evaluation 5/9/2019
67
3.6 Evaluation of Expressions(Cont’)
Virtues of postfix notation the need for parentheses is eliminated the priority of the operators is not relevant the expression is evaluated by making a left to right scan 5/9/2019
68
3.6 Evaluation of Expressions(Cont’)
void eval(expression e) // Evaluate the postfix expression e. It is assumed that the // last token (a token is either an operator, operand, or ‘#’) // in e is '#'. A function NextToken is used to get the next // token from e. The function uses the stack { Stack<token> stack; // initialize stack token x; for(x = NextToken(e); x != '#'; x = NextToken(e)) if (x is an operand) stack.Add(x) // add to stack else { // operator remove the correct number of operands for operator x from stack; Perform the operation x and store the result (if any) onto the stack; } } // end of eval Program 3.18 : Evaluating postfix expressions 5/9/2019
69
3.6 Evaluation of Expressions(Cont’)
void postfix(expression e) // Output the postfix form of the infix expression e.NextToken // and stack are as in function eval (Program 3.18). It is assumed that // the last token in e is ‘#.’ Also, ‘#’ is used at the bottom of the stack { Stack<token> stack; // initialize stack token y; stack.Add(‘#’); for (token x = NextToken(e); x != ‘#’; x = NextToken(e)) if is (s is an operand) cout <<x; else if (x == ‘)’) // unstack until ‘(‘ for (y = *stack.Delete(y); y != ‘(‘; y=* stack.Delete(y)) cout <<y; else { // x is an operator for (y = *stack.Delete(y); isp(y) <=icp(x); y = *stack.Delete(y)) cout <<y; stack.Add(y); // restack the last y that was unstacked stack.Add(x); } 5/9/2019
70
3.6 Evaluation of Expressions(Cont’)
// end of expression; empty stack while (!stack.IsEmpty()) cout <<*stack.Delete(y); } // end of postfix Program 3.19 : Converting from infix to postfix form 5/9/2019
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.