470 likes | 506 Views
Data Structures and Algorithms. Stack. 1. The Stack ADT. Introduction to the Stack data structure Designing a Stack class using dynamic arrays Linked Stacks Some Applications of Stacks. 2. 1. Introduction to the Stack Data Structure.
E N D
Data Structures and Algorithms Stack 1
The Stack ADT • Introduction to the Stack data structure • Designing a Stack class using dynamic arrays • Linked Stacks • Some Applications of Stacks 2
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 pop: remove from top 3
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 pop: remove from top 4
Example 5
Example push top ++top top top top top-- pop 6
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 7
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 8
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. 9
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 (); // Destructor 10
A Stack Class Definition // Member Functions void push(Type & ); // Push Type pop(); // Pop Type stackTop() const; // retrieve top value 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" 11
A Stack Class Definition Stackt (int s) //constructor { MaxSize = s; stack = new Type [MaxSize]; top = -1; } public void push(Type & i) { top++; stack[top] = I;} // increment top, insert item Type pop() {Type result = stack [top]; top--; return result; } Type stackTop() const {Type result = stack [top]; return result; // not removed} 12
A Stack Class Definition bool stackIsEmpty() const • { retrun (top == -1); } • bool stackIsFull() const; • {retrun (top == MaxSize – 1) ;} • ~Stackt () • {delete[] stack ;} 13
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) 14
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 15
Push Operation Last First top 2 3 New push(v): NodePointer pnew = new node ; pnew->e = v; pnew->next = top; top = pnew; 1 pnew 16
2 3 New 1 pnew Push Operation Last First top push(v): NodePointer pnew = new node ; pnew->e = v; pnew->next = top; top = pnew; 17
Pop Operation 1 cursor top 3 2 pop(v): v = top->e; cursor = top; top = top->next; delete cursor; 18
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(); // Pop 19
Linked Stack Class void stackTop() 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 • node() : e(value), next(link){} }; // end of class node declaration 20
Linked Stack Class typedef node * NodePointer; NodePointer top; // pointer to top }; #endif// STACKL_H 21
Linked Stack Class // STACKL.cpp • #include “StackL.h” • // constructor • StackL : : StackL {top=0;} • // Destructor • StackL : :- StackL { • StackL : :NodePointer currPtr = top, nextPtr; • while (currPtr != 0) { • nextPtr = currPtr->next; • delete currPtr; • currPtr = nextPtr; • } 22
Linked Stack Class // STACKL.cpp • #include “StackL.h” • // empty() • bool StackL : :stackIsEmpty() const • {return (top == 0)}; • // push() • void StackL : :push(Type &value) • { top = new StackL : :node(value, top); }/* The push operation is simple insertion at the beginning of a linked list. We get a new node containing the item to be added to the stack and have it point to the top node in the stack. The node constructor sets the data part of the new node equal to value and the next part equal to top pointer.*/ 23
Linked Stack Class // STACKL.cpp • #include “StackL.h” • // top() • Type StackL : : stackTop() const • { if (! stackIsEmpty()) return (top->data); else cout<<“Empty”;} • //pop() • void StackL : :pop() • { if (! stackIsEmpty()) Stack::NodePointer ptr= Top; Top = Top->next; • delete ptr; else cout<<“Empty”;} 24
4. Some Applications of Stacks • Run-time stack used in function calls. • Conversion from Decimal to Hexadecimal • Balancing Enclosure Symbols. • Evaluation of Postfix Expressions. • Converting Infix Expressions to Postfix. 25
(b) Decimal to Hexadecimal Conversion // Covert from Decimal to Hexadecimal string DEC-to_HEX(n) { Stackt <char> s; string H = “”; do { char c; rem = n % 16; n = n / 16; if (rem < 10) c = char (('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; } 31
(c) 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; 32
(c)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; } 33
(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 • Reverse Polish Notation (RPN) or “postfix”)(many compilers first transform these infix expressions into prefix) • does without parentheses. e.g. the above expression is: A B + C D E + - * • Postfix expressions like A B + are evaluated as A + B 36
Evaluation of Postfix Expressions The idea is: • The compiler scans 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. 38
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 39
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 40
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) 41
(e) 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 42
(e) Conversion from Infix to Postfix Expressions Example : convert the 7*8-(2+3) from infix to postfix 43
(e) Conversion from Infix to Postfix Expressions Example : convert the 7*8-(2+3) from infix to postfix 44
(e) Conversion from Infix to Postfix Expressions Example : convert the 7*8-(2+3) from infix to postfix Assignment: write a c++ program to convert from infix to postifx 45