Presentation is loading. Please wait.

Presentation is loading. Please wait.

1 Data Structures and Algorithms Stack. 2 The Stack ADT Introduction to the Stack data structure Designing a Stack class using dynamic arrays Linked Stacks.

Similar presentations


Presentation on theme: "1 Data Structures and Algorithms Stack. 2 The Stack ADT Introduction to the Stack data structure Designing a Stack class using dynamic arrays Linked Stacks."— Presentation transcript:

1 1 Data Structures and Algorithms Stack

2 2 The Stack ADT Introduction to the Stack data structure Designing a Stack class using dynamic arrays Linked Stacks Some Applications of Stacks

3 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 4 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

5 5 Example

6 6 Example top ++toptop push pop top top--

7 7 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 8 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 9 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 10 // 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 11 // 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" A Stack Class Definition

12 12 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} A Stack Class Definition

13 13 bool stackIsEmpty() const { retrun (top == -1); } bool stackIsFull() const; {retrun (top == MaxSize – 1) ;} ~Stackt () {delete[] stack ;} A Stack Class Definition

14 14 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

15 15 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

16 16 Push Operation top First pnew Last New 2 3 push(v): NodePointer pnew = new node ; pnew->e = v; pnew->next = top; top = pnew; 1

17 17 Push Operation top First Last 2 3 push(v): NodePointer pnew = new node ; pnew->e = v; pnew->next = top; top = pnew; pnew New 1

18 18 Pop Operation 2 3 cursor top pop(v): v = top->e; cursor = top; top = top->next; delete cursor; 1

19 19 // 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();// Pop Linked Stack Class

20 20 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 Linked Stack Class

21 21 typedef node * NodePointer; NodePointer top;// pointer to top }; #endif // STACKL_H Linked Stack Class

22 22 // 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; } Linked Stack Class

23 23 // 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.*/ Linked Stack Class

24 24 // 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”;} Linked Stack Class

25 25 Run-time stack used in function calls. Conversion from Decimal to Hexadecimal Balancing Enclosure Symbols. Evaluation of Postfix Expressions. Converting Infix Expressions to Postfix. 4. Some Applications of Stacks

26 26 (a) Run-time stack used in function calls

27 27 (a) Run-time stack used in function calls

28 28 (a) Run-time stack used in function calls

29 29 (a) Run-time stack used in function calls

30 30 (a) Run-time stack used in function calls

31 31 // Covert from Decimal to Hexadecimal string DEC-to_HEX(n) { Stackt 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; } (b) Decimal to Hexadecimal Conversion

32 32 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; (c) Balancing Enclosure Symbols

33 33 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; } (c)Balancing Enclosure Symbols

34 34 (c)Balancing Enclosure Symbols

35 35 (c)Balancing Enclosure Symbols

36 36 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 (c) Evaluation of Postfix Expressions

37 37 (c) Evaluation of Postfix Expressions

38 38 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. Evaluation of Postfix Expressions

39 39 Evaluation of Postfix Expressions (Example) A B + C D E + - * R1 C D E + - * R1 C R2 - * R1 R3 * R1 R3 * = RESULT

40 40 (2+3) * (2- (4+1)) → 2 3 + 2 4 1 + - * Evaluation of Postfix Expressions (Example) 2 3 + 2 4 1 + - * 5 2 4 1 + - * 5 2 5 - * 5 -3 * 5 -3 * = RESULT = -15

41 41 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)

42 42 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 (e) Conversion from Infix to Postfix Expressions

43 43 Example : convert the 7*8-(2+3) from infix to postfix (e) Conversion from Infix to Postfix Expressions

44 44 Example : convert the 7*8-(2+3) from infix to postfix (e) Conversion from Infix to Postfix Expressions

45 45 Example : convert the 7*8-(2+3) from infix to postfix Assignment: write a c++ program to convert from infix to postifx (e) Conversion from Infix to Postfix Expressions


Download ppt "1 Data Structures and Algorithms Stack. 2 The Stack ADT Introduction to the Stack data structure Designing a Stack class using dynamic arrays Linked Stacks."

Similar presentations


Ads by Google