Download presentation
Presentation is loading. Please wait.
Published byBernard Simmons Modified over 8 years ago
1
Prof. Amr Goneid, AUC1 CSCE 210 Data Structures and Algorithms Prof. Amr Goneid AUC Part 2a. Simple Containers: The Stack
2
Prof. Amr Goneid, AUC2 The Stack ADT Introduction to the Stack data structure Designing a Stack class using dynamic arrays Linked Stacks Some Applications of Stacks
3
Prof. Amr Goneid, AUC3 1. Introduction to the Stack Data Structure A simple data container consisting of a linear list of elements Access is by position (order of insertion) All insertions and deletions are done at one end, called top Last In First Out (LIFO) structure Two basic operations: push: add to top, complexity is O(1) pop: remove from top, complexity is O(1)
4
Prof. Amr Goneid, AUC4 Example
5
5 Example top ++toptop push pop top top--
6
Prof. Amr Goneid, AUC6 http://www.cosc.canterbury.ac.nz/people/ mukundan/dsal/StackAppl.htmlDemo
7
Prof. Amr Goneid, AUC7 Run-time stack used in function calls Page-visited history in a Web browser Undo sequence in a text editor Removal of recursion Conversion of Infix to Postfix notation Evaluation of Postfix expressions Reversal of sequences Checking for balanced symbols Some Stack Applications
8
Prof. Amr Goneid, AUC8 Stack Class Operations construct: construct an empty stack stackIsEmpty bool : return True if stack is empty stackIsFull bool : return True if stack is full push(el) : add element (el) at the top pop(el): retrieve and remove the top element stackTop(el): retrieve top element without removing it
9
Prof. Amr Goneid, AUC9 The stack may be implemented as a dynamic array. The capacity (MaxSize) will be input as a parameter to the constructor (default is 128) The stack ADT will be implemented as a template class to allow for different element types. 2. Array Based Stack Class Definition
10
Prof. Amr Goneid, AUC10 // File: Stackt.h // Stack template class definition. // Dynamic array implementation #ifndef STACKT_H #define STACKT_H template class Stackt { public: Stackt (int nelements = 128);// Constructor ~Stackt ();// Destructor A Stack Class Definition
11
Prof. Amr Goneid, AUC11 // Member Functions void push(Type );// Push void pop(Type &);// Pop void stackTop(Type &) const;// retrieve top bool stackIsEmpty() const;// Test for Empty stack bool stackIsFull() const;// Test for Full stack private: Type *stack;// pointer to dynamic array int top, MaxSize; }; #endif // STACKT_H #include "Stackt.cpp" A Stack Class Definition
12
Prof. Amr Goneid, AUC12 // File: Stackt.cpp // Stack template class implementation #include using namespace std; // Constructor with argument, size is nelements, default is 128 template Stackt ::Stackt(int nelements) { MaxSize = nelements; stack = new Type[MaxSize]; top = -1; } A Stack Class Implementation
13
Prof. Amr Goneid, AUC13 // Destructor template Stackt ::~Stackt() { delete [ ] stack;} // Push template void Stackt ::push(Type v) { if(stackIsFull()) cout << "Stack Overflow"; else stack[++top] = v; } A Stack Class Implementation
14
Prof. Amr Goneid, AUC14 // Pop template void Stackt ::pop(Type &v) { if(stackIsEmpty()) cout << "Stack Underflow"; else v = stack[top--]; } A Stack Class Implementation
15
Prof. Amr Goneid, AUC15 // Retrieve stack top without removing it template void Stackt ::stackTop(Type &v) const { if(stackIsEmpty()) cout << "Stack Underflow"; else v = stack[top]; } A Stack Class Implementation
16
Prof. Amr Goneid, AUC16 // Test for Empty stack template bool Stackt ::stackIsEmpty() const { return (top < 0); } // Test for Full stack template bool Stackt ::stackIsFull() const { return (top >= (MaxSize-1)); } A Stack Class Implementation
17
Prof. Amr Goneid, AUC17 int main() // Testing the Stackt Class {// Reverse a string and stack copy Stackt s1; char c; string instring = "Testing Stack Class"; string outstring = ""; cout << instring << endl; int L = instring.length(); cout << "Pushing characters on s1\n"; for (int i = 0; i < L; i++) s1.push(instring.at(i)); cout << "Copying s1 to s2\n"; Stackt s2 = s1; A Driver Program to Test Class
18
Prof. Amr Goneid, AUC18 cout << "Popping characters from s1\n"; while(!s1.stackIsEmpty()) { s1.pop(c); outstring = outstring + c; } cout << outstring << endl; cout <<"s1 is now empty. Trying to pop from empty s1\n"; s1.pop(c); cout << "Now popping contents of s2" << endl; while(!s2.stackIsEmpty()) { s2.pop(c); cout << c;} cout<< endl; return 0; } A Driver Program to Test Class
19
Prof. Amr Goneid, AUC19 Output: Testing Stack Class Pushing characters on s1 Copying s1 to s2 Popping characters from s1 ssalC kcatS gnitseT s1 is now empty. Trying to pop from empty s1 Stack Underflow Now popping contents of s2 ssalC kcatS gnitseT Press any key to continue A Driver Program to Test Class
20
Prof. Amr Goneid, AUC20 A stack can be implemented as a linked structure. Requires more space than array implementations, but more flexible in size. Easy to implement because operations are at the top (in this case the head node) 3. Linked Stacks
21
Prof. Amr Goneid, AUC21 Node Specification // The linked structure for a node can be // specified as a Class in the private part of // the main stack class. class node// Hidden from user { public: Type e;// stack element node *next;// pointer to next node }; // end of class node declaration typedef node * NodePointer; NodePointer top;// pointer to top
22
Prof. Amr Goneid, AUC22 Push Operation top First pnew Last New 2 3 push(v): Insert at top NodePointer pnew = new node ; pnew->e = v; pnew->next = top; top = pnew; 1
23
Prof. Amr Goneid, AUC23 Pop Operation 2 3 cursor top pop(v): Remove from top v = top->e; cursor = top; top = top->next; delete cursor; 1
24
Prof. Amr Goneid, AUC24 // File: StackL.h // Linked List Stack class definition #ifndef STACKL_H #define STACKL_H template class StackL { public: StackL();// Constructor ~StackL();// Destructor void push(Type );// Push void pop(Type &);// Pop Linked Stack Class
25
Prof. Amr Goneid, AUC25 void stackTop(Type &) const;// retrieve top bool stackIsEmpty() const;// Test for Empty stack private: // Node Class class node { public: Type e;// stack element node *next;// pointer to next node }; // end of class node declaration Linked Stack Class
26
Prof. Amr Goneid, AUC26 typedef node * NodePointer; NodePointer top;// pointer to top }; #endif // STACKL_H #include "StackL.cpp" Linked Stack Class
27
Prof. Amr Goneid, AUC27 Conversion from Decimal to Hexadecimal Balancing Enclosure Symbols Evaluation of Postfix Expressions Converting Infix Expressions to Postfix Computing Spans Backtracking Hanoi Towers 4. Some Applications of Stacks
28
Prof. Amr Goneid, AUC28 // Covert from Decimal to Hexadecimal string DEC-to_HEX(n) { Stackt s; string H = “”; do {rem = n % 16;n = n / 16; if (rem < 10) c = char (int('0') + rem); else c = char (int('A') + rem - 10); s.push(c); }while ( n != 0); while (!s.stackIsEmpty()) {s.pop(c); H = H + c;} return H; } (a) Decimal to Hexadecimal Conversion
29
Prof. Amr Goneid, AUC29 Given a text file containing a sequence of characters, we want to check for balancing of the symbols ( ), [ ], { }. Algorithm: bool EnclosureBalance (filename) { Open file filename; Initialize an empty stack of characters; balanced = true; for each character (ch) read until end of file : { If (ch is a left symbol) push ch on the stack; (b) Balancing Enclosure Symbols
30
Prof. Amr Goneid, AUC30 else if (ch is a right symbol) then if (stack is empty) balanced = false; else { pop the stack; if (popped symbol is not the corresponding left symbol) balanced = false; } At the end of the file, if (stack is not empty) balanced = false; return balanced; } Balancing Enclosure Symbols
31
Prof. Amr Goneid, AUC31 {a * (b + c) }Balanced {a * (b + c [ i ] }Not Balanced Balancing Enclosure Symbols ( {{{ [ ((( {{{{{
32
Prof. Amr Goneid, AUC32 Regular expressions are written in “infix” notation, i.e., operator between two operands, e.g., (A+B) * (C- (D+E)) Parentheses are used to force precedence (c) Evaluation of Postfix Expressions
33
Prof. Amr Goneid, AUC33 Reverse Polish Notation (RPN) or “postfix” does without parentheses (invented by Lukasiewics). e.g. the expression (A+B) * (C- (D+E)) becomes: A B + C D E + - * Postfix expressions like A B + are evaluated as A + B Evaluation of Postfix Expressions
34
Prof. Amr Goneid, AUC34 The idea is: Scan from left to right until an operator (+,-,*,/) is encountered. Apply operator between the previous operands. Replace the two previous operands by the result. This suggests to use a stack to store operands and the results. Evaluation of Postfix Expressions
35
Prof. Amr Goneid, AUC35 Initialize a stack (S) of characters For each character from left to right Get next character If operand, push it on S If an operator: –Pop two values (error if there are no two values) –Apply operator –Push result back onto (S) At the end, result is on top of (S) (the only value, otherwise an error) Evaluation of Postfix Expressions (Algorithm)
36
Prof. Amr Goneid, AUC36 (A+B) * (C- (D+E)) → A B + C D E + - * (2+3)*(2- (4+1)) → 2 3 + 2 4 1 + - * Evaluation of Postfix Expressions (Example) E DDD+E BCCCCC-(D+E) AAA+B Final 1 445 32222-3 22555555-15
37
Prof. Amr Goneid, AUC37 Initialize an operator stack, s While not end of infix expression do the following: read next symbol in case the symbol is: an operand:write the operand ‘ ( ‘ :push onto s ‘ ) ’ :pop and write all operators until encountering ‘ ( ‘, then pop ‘ ( ‘ ‘ * ’ or ‘ / ’ :1-pop and write all ‘ * ’ and ‘ / ’ operators from the top down to but not including the top most ‘ ( ‘, ’ + ’, ’ - ’ or to the bottom of the stack 2-push the ‘ * ’ or ‘ / ’ ‘ + ’ or ‘ - ’ :1-pop and write all operators from the top down to but not including the topmost ‘ ( ‘ or to the bottom of the stack 2-push the ‘ + ’ or ‘ - ’ End of exp:pop and write all operators (d) Conversion from Infix to Postfix Expression
38
Prof. Amr Goneid, AUC38 Example: (A+B) * (C- (D+E)) → A B + C D E + - * Conversion from Infix to Postfix Expressions
39
Prof. Amr Goneid, AUC39 (e) Computing Spans Given an an array X, the span S[i] of X[i] is the maximum number of consecutive elements X[j] immediately preceding and including X[i] and such that X[j] ≤ X[i]. Spans have applications to financial analysis. Example: i01234567 X63412354 S11212361
40
Prof. Amr Goneid, AUC40 Computing Spans Algorithm Computing Spans with a Stack Keep in a stack the indices of the elements visible when “looking back”. Scan the array from left to right. Let i be the current index. Pop indices from the stack until stack top = index j such that X[i] < X[j]. Set S[i] ← i − j Push current index i onto the stack
41
Prof. Amr Goneid, AUC41 Computing Spans Algorithm Linear Algorithm using a Stack spans(X,S, n) { A ← new empty stack for i ← 0 to n − 1 while (!A.stackIsEmpty() && X[A.top()] ≤ X[i] ) A.pop() if (A.stackIsEmpty() ) then S[i] ← i + 1 else S[i] ← i − A.top() A.push(i) }
42
(f) Backtracking (Maze Problem) Prof. Amr Goneid, AUC42
43
Prof. Amr Goneid, AUC43 Backtracking (Maze Problem) in out A B C D E FG
44
Prof. Amr Goneid, AUC44 We may choose to move in the order: South – East – North – West A stack is used to record the tracks. When we move on a new track, we push it on the stack. When we run out of tracks, we backtrack by popping the last track from the stack. Later in the course, we will do this using a recursive algorithm using the system stack. The algorithm is called Depth First Search Backtracking (Maze Problem)
45
Prof. Amr Goneid, AUC45 The stack will develop as shown Backtracking (Maze Problem) D CCEG BBBBBFF AAAAAAAA steps popexit
46
(g) The Towers of Hanoi http://www.cosc.canterbury.ac.nz/mukund an/dsal/ToHdb.html Prof. Amr Goneid, AUC46
47
Prof. Amr Goneid, AUC47 Learn on your own about: Use of run-time stack in function calls Removing recursion using a stack
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.