Stack
Er. Harpreet Kaur harpreet_cse@[Link]
Abstract Data Type
Abstract
Data Type as a design tool Concerns only on the important concept or model No concern on implementation details. Stack & Queue is an example of ADT An array is not ADT.
What is the difference?
Stack & Queue vs. Array Arrays are data storage structures while stacks and queues are specialized DS and used as programmers tools. Stack a container that allows push and pop
Queue - a container that allows Enqueue and Dequeue
No concern on implementation details.
In an array any item can be accessed, while in these data structures access is restricted.
They are more abstract than arrays.
Stacks
Allows
access to only the last item inserted.
An
item is inserted or removed from the stack from one end called the top of the stack.
mechanism is called Last-In-First-Out (LIFO).
This
Some
of the applications are : microprocessors, some older calculators etc.
Stack
A stack is a list in which insertion and deletion take place at the same end
This end is called top The other end is called bottom
Stacks are known as LIFO (Last In, First Out) lists.
The last element inserted will be the first to be retrieved
Basic operations of stack
Push Pop
Implementations of stacks using
array linked list
Push and Pop
Primary Push
operations: Push and Pop
Add an element to the top of the stack
Remove the element at the top of the stack
Pop
empty stack
push an element top
push another
pop
top
top
B A
top
Implementation of Stacks
Any
list implementation could be used to implement a stack
Arrays (static: the size of stack is given initially)
Linked lists (dynamic: never become full)
Array Representation of Stacks
Attributes of Stack
Represented as a one way list or a linear array STACK. A pointer variable TOP i.e. location of the top element of the stack. A variable MAXSTK i.e. the maximum size of stack
Stack Terminology
EMPTY :Stack is empty if TOP=0 or TOP = NULL FULL: Stack is full if TOP = MAXSTK, return false otherwise PUSH : Add an element to the top of stack POP : Delete the element at the top of stack PRINT: Print all the data in the stack OVERFLOW: In executing the procedure PUSH , if Stack is already full means TOP = MAXSTK then the condition is called OVERFLOW. UNDERFLOW : In executing the procedure POP , if Stack is already empty means TOP = NULL then the condition is called UNDERFLOW.
10
PUSH Operation
Algorithm
PUSH ( STACK ,TOP, MAXSTK, DATA) 1. If TOP = MAXSTK,
then : Print OVERFLOW and Exit. 2. Set TOP = TOP +1 3. Set STACK [ TOP ] = DATA 4. Exit
11
POP Operation
Algorithm
POP ( STACK ,TOP, DATA)
1. If TOP = 0,
then : Print UNDERFLOW and Exit. 2. Set DATA = STACK [ TOP ] 3. Set TOP = TOP -1 4. Exit
12
Linked Representation of Stacks
Represented
as a One way list or singly linked
list. Each element is represented as a node of linked list. Each node contains two parts:
INFO LINK
13
PUSH 5
POP
14
PUSH Operation
Algorithm :
PUSH_LS ( INFO,LINK,TOP,AVAIL,DATA)
1. If AVAIL = NULL, then write OVERFLOW and Exit. 2. Set NEW = AVAIL and AVAIL = LINK [AVAIL] 3. Set INFO[NEW] = DATA 4. Set LINK [NEW] = TOP 5. Set TOP = NEW 6. Exit
15
POP Operation
Algorithm :
POP_LS ( INFO,LINK,TOP,AVAIL,DATA)
1. If TOP = NULL, then write UNDERFLOW and Exit. 2. Set DATA = INFO[NEW] 3. Set TEMP = TOP and TOP = LINK[TOP] 4. Set LINK[TEMP] = AVAIL and AVAIL = TEMP 5. Exit
16
Application of Stacks: RPN (Reverse Polish Notation)
1. What is RPN (Reverse Polish Notation)? A notation for arithmetic expressions in which operators are written after the operands. Expressions can be written without using parentheses.
Developed by Polish logician, Jan Lukasiewics, in 1950's Infix notation: Postfix " (RPN): Prefix " : operators written between the operands operators written after the operands operators written before the operands
17
Examples:
INFIX
A + B
A * B + C
RPN (POSTFIX)
A B +
A B * C +
PREFIX
+ A B
+ * A B C
A * (B + C)
A - (B - (C - D)) A - B - C - D
A B C + *
A B C D - - A B - C - D -
* A + B C
- A - B - C D - - - A B C D
18
ARITHMETIC EXPRESSIONS
Infix Notation
A+B C-D E*F G/H
Prefix / Polish Notation
+AB -CD *EF /GH
Postfix / Reverse Polish Notation
AB+ CD EF* GH/
19
Postfix Expressions
Use stack to evaluate postfix expressions
When a number is seen, it is pushed onto the stack When an operator is seen, the operator is applied to the 2 numbers that are popped from the stack. The result is pushed onto the stack
Example
evaluate 6 5 2 3 + 8 * + 3 + *
The time to evaluate a postfix expression is O(N)
processing each element in the input consists of stack operations and thus takes constant time
20
21
Call is to push and return is to pop!
top fac(1) fac(2) fac(3) prod1=1 prod2=2*fac(1) prod3=3*fac(2)
22
Stack Application: postfix, infix expressions and calculator
expressions
Postfix
abc*+de*f+g*+ Operands are in a stack
Convert
infix to postfix
a+b*c+(d*e+f)*g a b c * + d e * f + g * + Operators are in a stack
Calculator
Adding more operators
23
Evaluating RPN Expressions
1.
Scan the expression from left to right to find an operator.
2. Locate ("underline") the last two preceding operands and combine them using this operator. 3. Repeat until the end of the expression is reached. Example: 2 3 2 3 2 7 2 7 2 7 2 7 2 8 16 4 + 5 6 4 + 5 6 5 6 - 5 6 - -1 - * -1 - * * - - * - - * * *
24
Stack Algorithm Receive: Return: An RPN expression. A stack whose top element is the value of RPN expression
1. Initialize an empty stack. 2. Repeat the following until the end of the expression is encountered: a. Get next token (constant, variable, arithmetic operator) in the RPN expression. b. If token is an operand, push it onto the stack. If it is an operator, then: (i) Pop top two values from the stack. If stack does not contain two items, signal error due to a malformed RPN and terminate evaluation. (ii) Apply the operator to these two values. (iii) Push the resulting value back onto the stack. 3. When the end of expression encountered, its value is on top of the stack (and, in fact, must be the only value in the stack).
A B C + D E - - *
25
Sample RPN Evaluation
Example: Push Push Push Read Push Push Push Read Push Read Push Read Push 2 3 4 + Pop 4, Pop 3, 7 5 6 Pop 6, Pop 5, 5 - 6 = -1 -1 Pop -1, Pop 7, 7 - -1 = 8 8 * Pop 8, Pop 2, 2 * 8 = 16 16
-1 7 3
2 3 4 + 5 6 - - *
4 3
+ 4 = 7
6 5 7
2
8 2 16
26
Converting Infix to RPN
1.
By hand:
* B + C
+
Represent infix expression as an expression tree:
A
* (B + C)
*
((A
+ B) * C) / (D - E)
/
+
+
C A
Root
D
Node
Edg
D y
x
e
y
Nodes (Binary Tree 2 kids)
Children
27
Traverse
the tree in Left-Right-Parent order (postorder) to get RPN:
* A B + C * D E - / + C
D /
Traverse
tree in Parent-Left-Right order (preorder) to get prefix:
/
B * +
* + A B
C -
D E
C /
Traverse
tree in Left-Parent-Right order (inorder) to get infix must insert ()'s
((A
*
+
+ B)* C) /
(D )
- E)
28
2. By hand: "Fully parenthesize-move-erase" method:
1. 2. 3.
Fully parenthesize the expression. Replace each right parenthesis by the corresponding operator. Erase all left parentheses.
Examples:
* B + C
((A * B) + C) ((A B * C + A B * C +
* (B + C)
(A * (B + C) ) (A (B C + * A B C + *
Exercise:
((A
+ B) * C) / (D - E)
29
3. Use a stack! Stack Algorithm:
1. Initialize an empty stack of operators. 2. While no error has occurred and end of infix expression not reached a. Get next token in the infix expression. b. If token is (i) a left parenthesis: (ii) a right parenthesis:
Push it onto the stack. Pop and display stack elements until a left parenthesis is encountered, but do not display it. (Error if stack empty with no left parenthesis found.) If stack empty or token has higher priority than top stack element, push token onto stack. (Left parenthesis in stack has lower priority than operators) Otherwise, pop and display the top stack element; then repeat the comparison of token with new top stack item. Display it.
(iii) an operator:
(iv) an operand:
3. When end of infix expression reached, pop and display stack items until stack is empty.
30
Example: (A+B*C)/(D-(E-F)) Push ( Output Display A Push + A Display B AB Push * Display C ABC Read ) Pop *, Display *, ABC* Pop +, Display +, Pop ( ABC*+ Push / Push ( Display D ABC*+D Push Push ( Display E ABC*+DE Push Display F ABC*+DEF Read ) Pop -, Display -, Pop ( ABC*+DEFRead ) ABC*+DEF-Pop -, Display -, Pop (
* + ( + ( ( ( ( / ( / /
Pop /, Display /
ABC*+DEF--/
31
Static and dynamic objects
dynamic
is relative static variables are from a Stack dynamic variables are from a heap (seen later )
32
Array versus linked list implementations
Push,
pop, top are all constant-time operations in both array and linked list implementation
For array implementation, the operations are performed in very fast constant time