DSA Unit 2 Stack
DSA Unit 2 Stack
Stack
◆ Stack is a linear data structure
2
3
Operations of Stack
4
Implementation of Stack
5
Working of Stack Data Structure
◆ TOP variable is used to keep track of the top element in the stack.
● PUSH Operation : Increase the value of TOP by 1 and place the new element in the
position pointed to by TOP.
● POP Operation :Return the element pointed to by TOP and reduce its value by 1.
6
7
Algorithm of Stack
PUSH Operation
Algorithm push(stack, element)
if top==maxindex
write OverflowError("Stack is full")
else
{
top=top+1
stack[top] = element
}
8
Algorithm of Stack
POP Operation
Algorithm pop(stack)
if top==-1
write UnderflowError("Stack is empty")
else
{
element = stack[top]
top= top-1
}
return element
9
Implementation of Stack
10
Create Stack
11
Full Stack
12
Empty Stack
13
PUSH Operation
14
POP Operation
15
Complexity Analysis
PUSH Operation
◆ PUSH operation adds an element on top of the stack
◆ Time Complexity: O(1) PUSH Operation takes a single memory allocation operation which is
done in constant time.
16
Complexity Analysis
POP Operation
◆ POP operation removes the topmost element in the stack and returns an error if the stack is already
empty
◆ Time Complexity: O(1), In array implementation, only an arithmetic operation is performed i.e., the top
pointer is decremented by 1. This is a constant time function.
◆ Space Complexity : O(1), No extra space is utilized for deleting an element from the stack
17
Applications of STACK
● Reverse a word
● Browser history
● Undo/Redo Operations
● Function Calls
● Recursion
18
Arithmetic Expression
19
Evaluation of Arithmetic Expression
20
Evaluation of Arithmetic Expression
● Stack-organized computers are better suited for post-fix notation than infix notation
● Conversion from infix notation to postfix notation must take into consideration the operational hierarchy
21
Examples of Conversion
22
Example Conversion
23
Evaluate Postfix Expression using STACK
For example –
Infix notation: (2+4) * (4+6)
Post-fix notation: 2 4 + 4 6 + *
Result: 60
24
25
Evaluate 234*+
26
Evaluate 3 4 * 2 5 * +
27
Algorithm Evaluation of Postfix Expression
Algorithm postfix_evaluation(postfix_expression)
stack = []
return pop(stack)
28
Infix to Postfix Expression
29
Convert Infix a+b*c+d to Postfix
30
Convert Infix ((A + B) – C * (D / E)) + F to Postfix
31
D / E)) + F (-*( AB+C
/ E)) + F (-*( AB+CD
E)) + F (-*(/ AB+CD
)) + F (-*(/ AB+CDE
)+F (-* AB+CDE /
+F AB +CDE / * -
F + AB + CDE/ * -
empty + AB + CDE/ * - F
empty empty AB + CDE / * - F +
32
Examples Infix to Postfix
33
Infix to Prefix Expression
34
Algorithm for Infix to Prefix
35
36
37