440 likes | 593 Views
CSCE 210 Data Structures and Algorithms. Prof. Amr Goneid AUC Part 2a. Simple Containers: The Stack. The Stack ADT. Introduction to the Stack data structure Designing a Stack class using dynamic arrays Linked Stacks Some Applications of Stacks.
E N D
CSCE 210Data Structures and Algorithms Prof. Amr Goneid AUC Part 2a. Simple Containers: The Stack Prof. Amr Goneid, AUC
The Stack ADT • Introduction to the Stack data structure • Designing a Stack class using dynamic arrays • Linked Stacks • Some Applications of Stacks Prof. Amr Goneid, AUC
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) Prof. Amr Goneid, AUC
Example Prof. Amr Goneid, AUC
Example push top ++top top top top top-- pop Prof. Amr Goneid, AUC
Demo http://www.cosc.canterbury.ac.nz/people/mukundan/dsal/StackAppl.html Prof. Amr Goneid, AUC
Some Stack Applications • 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 Prof. Amr Goneid, AUC
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 Prof. Amr Goneid, AUC
2. Array Based Stack Class Definition • 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. Prof. Amr Goneid, AUC
A Stack Class Definition // File: Stackt.h // Stack template class definition. // Dynamic array implementation #ifndef STACKT_H #define STACKT_H template <class Type> class Stackt { public: Stackt (int nelements = 128); // Constructor Stackt (const Stackt <Type> &); // Copy Constructor ~Stackt (); // Destructor Prof. Amr Goneid, AUC
A Stack Class Definition // 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" Prof. Amr Goneid, AUC
A Stack Class Implementation // File: Stackt.cpp // Stack template class implementation #include <iostream> using namespace std; // Constructor with argument, size is nelements, default is 128 template <class Type> Stackt<Type>::Stackt(int nelements) { MaxSize = nelements; stack = new Type[MaxSize]; top = -1; } Prof. Amr Goneid, AUC
A Stack Class Implementation // Copy Constructor template <class Type> Stackt <Type> ::Stackt (const Stackt<Type> &original) :MaxSize(original.MaxSize), top(original.top) { stack = new Type[MaxSize]; for (int i = 0; i <= top; i++) stack[i] = original.stack[i]; } // Destructor template <class Type> Stackt <Type> ::~Stackt() { delete [ ] stack;} Prof. Amr Goneid, AUC
A Stack Class Implementation // Push template <class Type> void Stackt<Type>::push(Type v) { if(stackIsFull()) cout << "Stack Overflow"; else stack[++top] = v; } Prof. Amr Goneid, AUC
A Stack Class Implementation // Pop template <class Type> void Stackt<Type>::pop(Type &v) { if(stackIsEmpty()) cout << "Stack Underflow"; else v = stack[top--]; } Prof. Amr Goneid, AUC
A Stack Class Implementation // Retrieve stack top without removing it template <class Type> void Stackt<Type>::stackTop(Type &v) const { if(stackIsEmpty()) cout << "Stack Underflow"; else v = stack[top]; } Prof. Amr Goneid, AUC
A Stack Class Implementation // Test for Empty stack template <class Type> bool Stackt<Type>::stackIsEmpty() const { return (top < 0); } // Test for Full stack template <class Type> bool Stackt<Type>::stackIsFull() const { return (top >= (MaxSize-1)); } Prof. Amr Goneid, AUC
A Driver Program to Test Class int main() // Testing the Stackt Class { // Reverse a string and stack copy Stackt<char> 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<char> s2 = s1; Prof. Amr Goneid, AUC
A Driver Program to Test Class 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; } Prof. Amr Goneid, AUC
A Driver Program to Test Class 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 Prof. Amr Goneid, AUC
3. Linked Stacks • 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) Prof. Amr Goneid, AUC
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 Prof. Amr Goneid, AUC
Push Operation Last First top 2 3 New • push(v): • NodePointer pnew = new node ; • pnew->e = v; • pnew->next = top; • top = pnew; 1 pnew Prof. Amr Goneid, AUC
Pop Operation 1 cursor top 3 2 • pop(v): • v = top->e; • cursor = top; • top = top->next; • delete cursor; Prof. Amr Goneid, AUC
Linked Stack Class // File: StackL.h // Linked List Stack class definition #ifndef STACKL_H #define STACKL_H template <class Type> class StackL { public: StackL(); // Constructor ~StackL(); // Destructor void push(Type ); // Push void pop(Type &); // Pop Prof. Amr Goneid, AUC
Linked Stack Class 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 Prof. Amr Goneid, AUC
Linked Stack Class typedef node * NodePointer; NodePointer top; // pointer to top }; #endif// STACKL_H #include "StackL.cpp" Prof. Amr Goneid, AUC
4. Some Applications of Stacks • Conversion from Decimal to Hexadecimal • Balancing Enclosure Symbols • Evaluation of Postfix Expressions • Converting Infix Expressions to Postfix • Backtracking • Hanoi Towers Prof. Amr Goneid, AUC
(a) Decimal to Hexadecimal Conversion // Covert from Decimal to Hexadecimal string DEC-to_HEX(n) { Stackt <char> 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; } Prof. Amr Goneid, AUC
(b) Balancing Enclosure Symbols 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; Prof. Amr Goneid, AUC
Balancing Enclosure Symbols 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; } Prof. Amr Goneid, AUC
(c) Evaluation of Postfix Expressions • 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 Prof. Amr Goneid, AUC
Evaluation of Postfix Expressions • 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 Prof. Amr Goneid, AUC
Evaluation of Postfix Expressions 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. Prof. Amr Goneid, AUC
Evaluation of Postfix Expressions (Example) A B + C D E + - * R1 C D E + - * R1 C R2- * R1 C R2 - * R1 R3 * R1 R3 * = RESULT Prof. Amr Goneid, AUC
Evaluation of Postfix Expressions (Example) (2+3) * (2- (4+1))→ 2 3 + 2 4 1 + - * 2 3 + 2 4 1 + - * 5 2 4 1 + - * 5 2 5- * 5 2 5 - * 5 -3 * 5 -3 * = RESULT = -15 Prof. Amr Goneid, AUC
Evaluation of Postfix Expressions (Algorithm) • 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) Prof. Amr Goneid, AUC
(d) Conversion from Infix to Postfix Expressions 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 Prof. Amr Goneid, AUC
(e) Backtracking (Maze Problem) Prof. Amr Goneid, AUC
Backtracking (Maze Problem) in A out F G B E C D Prof. Amr Goneid, AUC
Backtracking (Maze Problem) • 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 Prof. Amr Goneid, AUC
Backtracking (Maze Problem) • The stack will develop as shown pop exit steps Prof. Amr Goneid, AUC
(f) The Towers of Hanoi http://www.cosc.canterbury.ac.nz/mukundan/dsal/ToHdb.html Prof. Amr Goneid, AUC
Learn on your own about: • Use of run-time stack in function calls • Removing recursion using a stack Prof. Amr Goneid, AUC