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 (const Stackt &);// Copy Constructor ~Stackt ();// Destructor A Stack Class Definition

11 11 // 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 12 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

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

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

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

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

17 17 // 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

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

19 19 typedef node * NodePointer; NodePointer top;// pointer to top }; #endif // STACKL_H #include "StackL.cpp" Linked Stack Class

20 20 Conversion from Decimal to Hexadecimal Balancing Enclosure Symbols Evaluation of Postfix Expressions Converting Infix Expressions to Postfix Backtracking 4. Some Applications of Stacks

21 21 // 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

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

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

24 24 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” 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

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

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

27 27 (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

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

29 29 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 Expressions

30 30 (e) Backtracking (Maze Problem) A Maze can be modeled as nodes (decision points) and edges (tracks). A Backtracking method can be used to find the way to the exit starting from an entrance. in out A B C D E FG

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

32 32 The stack will develop as shown Backtracking (Maze Problem) D CCEG BBBBBFF AAAAAAAA steps popexit


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