STACK
1
Abstract Data Types
•An Abstract Data Type is some sort of data together with set of functions (interface) that operate on the data.
•To simplify the process of solving problems, we combine the data structures with their operations and we call this Abstract Data Types (ADTs).
•An ADT consists of two parts:
• Declaration of data
• Declaration of operations
• Ex. Stack, Queue, Tree, and Graph.
2
Stack
• Stack is a linear data structure in which the insertion and deletion operations are performed at only one end.
• In a stack, adding and removing of elements are performed at single position which is known as "top".
• That means, new element is added at top of the stack and an element is removed from the top of the stack.
• In stack, the insertion and deletion operations are performed based on LIFO (Last In First Out) principle.
3
❑
Stack uses LIFO (Last-In-First-Out) mechanism while storing the data in data structures i.e. the last element inserted into the stack is the first element that gets deleted.
❑
Common operations of it are:
❑
creating the stack,
❑
pushing an element onto the stack,
❑
popping an element from stack,
❑
finding the current top of the stack,
❑
finding number of elements in the stack, etc.
4
Stack Operations
•In stacks, insertion and deletion takes place at the same place called top.
•Inserting an element into a stack is called push operation.
•Deleting an element from the stack is called pop operation.
•Stack is said to be in Overflow state when it is completely full and is said to be in Underflow state if it is completely empty.
5
6
Implementation of Stacks
•Static Implementation
• Stack is represented as an array
•Dynamic Implementation
• Stack is represented as a linked list
Note:
1.When stack is implemented using array, that stack can organize only limited number of elements.
2. When stack is implemented using linked list, that stack can organize unlimited number of elements.
7
Push operation
0 10
Initially stack is assumed to be empty --- >
top=-1
20 10
30 20 10
40 30 20 10
Now, increment top Then push the element
top
50 40 30 20 10 1
2
3
4
Initial value of top=-1 final value of top=4 i.e, top should not exceed max – 1 in array implementation.
8
Note:-
•STACK is the name of array.
•TOP is a variable which contains location of the top element of the stack.
•MAXSTK is the maximum no. of elements that can be held by stack.
9
POP Operation
• POP(STACK, TOP, ITEM)
This algorithm deletes the top element of stack and assigns it to variable ITEM.
1.[Stack has an item to be removed?]
If TOP = -1 , then : Print: UNDERFLOW, and Return.
2. Set ITEM = STACK[TOP]. [Assigns TOP element to ITEM]
3. Set TOP=TOP -1 . [Decrease TOP by 1.]
4. Return.
10
Stack using arrays : example – push() and pop()
int StackArray[50]; // StackArray can contain up to 50 numbers int top=-1; // index of the top element of the stack // -1 used to indicate an empty stack
void push(int element) {
top++;
StackArray[top] = element;
}
int pop() {
int element = StackArray[top];
top--;
return element;
}
11
display() - Displays the elements of a Stack
We can use the following steps to display the elements of a stack...
Step 1: Check whether stack is EMPTY. (top == -1)
Step 2: If it is EMPTY, then display "Stack is EMPTY!!!" and terminate the function.
Step 3: If it is NOT EMPTY, then define a variable 'i' and initialize with top. Display stack[i] value and decrement i value by one (i--).
Step 4: Repeat above step until i value becomes '0'.
12
What will be the contents of the stack after the following sequence of operations?
push(A) push(B) pop
push(C) push(D) push(E) pop
pop pop pop
stack
13
What will be the contents of the stack after the following sequence of operations?
push(A) push(B) pop
push(C) push(D) push(E) pop
pop pop pop
A
stack
14
What will be the contents of the stack after the following sequence of operations?
push(A) push(B) pop
push(C) push(D) push(E) pop
pop pop pop
B A
stack
15
What will be the contents of the stack after the following sequence of operations?
push(A) push(B) pop
push(C) push(D) push(E) pop
pop pop pop
A
stack
16
What will be the contents of the stack after the following sequence of operations?
push(A) push(B) pop
push(C) push(D) push(E) pop
pop pop pop
E D C A
stack
17
What will be the contents of the stack after the following sequence of operations?
push(A) push(B) pop
push(C) push(D) push(E) pop
pop pop pop
D C A
stack
18
What will be the contents of the stack after the following sequence of operations?
push(A) push(B) pop
push(C) push(D) push(E) pop
pop pop pop
C A
stack
19
What will be the contents of the stack after the following sequence of operations?
push(A) push(B) pop
push(C) push(D) push(E) pop
pop pop pop
A
stack
20
What will be the contents of the stack after the following sequence of operations?
push(A) push(B) pop
push(C) push(D) push(E) pop
pop pop pop
stack
21
22
Applications of Stacks
23
Applications of Stacks
•Stacks are extensively used in computer applications-system software like compilers, operating systems etc.
•Used in function calls, parameters are passed through stacks.
•Many compilers store the local variables inside a function on the stack.
24
Applications of stacks contd…
•Conversion of one notation of expression to another.
•Evaluation of expressions.
•Balancing symbols to check for correctness of an expression.
25
Expressions
• An expression is a collection of operators and operands that represents a specific value.
• In above definition, operator is a symbol which performs a particular task like arithmetic operation or logical operation or conditional
operation etc.
• Operands are the values on which the operators can perform the task.
Here operand can be a direct value or variable or address of memory location
26
Types of Notations/Expressions
•Infix Notation
– e.g : A+B
• Prefix Notation/ Polish Notation
– e.g : +AB
• Postfix Notation/ Reverse Polish Notation
– e.g : AB+
When an infix expression is to be converted into prefix or postfix Precedence rules and associativity rules follows.
27
Why postfix representation of the expression?
• The compiler scans the expression either from left to right or from right to left.
Example: consider the expression a + b * c + d
• The compiler first scans the expression to evaluate the expression b * c, then again scan the expression to add a to it. The result is
then added to d after another scan.
• The repeated scanning makes it very in-efficient. It is better to convert the expression to postfix(or prefix) form before evaluation.
•The postfix expressions can be evaluated easily using a stack.
28
Advantages of Postfix Notation
•No parenthesis required.
•No need to remember precedence and associativity rules of various operators.
•When an infix expression is to be converted into prefix or postfix BODMAS rules and associativity rules follows
(Highest)
•^ Right associative
•*,/ left associative
•+,- left associative
(lowest)29
Expressions contd…
For unparenthesized operators of same precedence, the order is assumed to be left to right except in the case of exponentiation.
Ex: A + B +C means (A + B) + C
A $ B $ C means A $(B $ C),
where $ stands for exponentiation30
Ex:
Infix Postfix
A+B AB+
A+B-C AB+C-
(A+B)*(C-D) AB+CD-*
A$B*C-D+E/F/(G+H) AB$C*D-EF/GH+/+
((A+B)*C-(D-E))$(F+G) AB+C*DE- - FG+$
A-B/(C*D$E) ABCDE$*/ -
……….
Infix Prefix
A+B +AB
A+B-C -+ABC
(A+B)*(C-D) *+AB-CD
A$B*C-D+E/F/(G+H) +-*$ABCD//EF+GH ((A+B)*C-(D-E))$(F+G) $-*+ABC-DE+FG
A-B/(C*D$E) -A/B*C$DE
31
C onvert an Infix to Postfix Using Stack:
• To convert Infix Expression into Postfix Expression using a stack data structure, We can use the following steps...
1.Read all the symbols one by one from left to right in the given Infix Expression.
2.If the reading symbol is operand, then directly print it to the result (Output).
3.If the reading symbol is left parenthesis '(', then Push it on to the Stack.
4.If the reading symbol is right parenthesis ')', then Pop all the contents of stack until respective left parenthesis is popped and print each popped symbol to the result.
5.If the reading symbol is operator (+ , - , * , / etc.,), then Push it on to the Stack. However, first pop the operators which are already on the stack that have higher or equal precedence than current operator and print them to the result.
32
Algorithm: Postfix(Q, P)
[Suppose Q is an arithmetic expression written in infix notation. This algorithm finds the equivalent postfix expression P]
1. Set Q as input Expression, S is stack and P is output array.
2. Scan Q from left to right, repeat step 3 to 6 until infix expression is scanned 3. If operand put it to P (output array)
4. If scanned character is an ‘(‘, push it onto the stack S.
5. If operator then
1. Repeatedly pop from stack S and add to P each operator that has the same precedence or higher precedence than the operator encountered.
2. Add/push operator to stack S
6.
If scanned character is an ‘)’ then
(a) Pop from stack S and add to P each operator until a left opening parenthesis ‘(‘ is
encountered.
(b) Remove left parenthesis ( and do not add to output array P)
1.
Pop and output from the stack until it is not empty.
33
Ex: a+b*c+(d*e+f)*g
stack
output
34
Ex: a+b*c+(d*e+f)*g
stack
a
output
35
Ex: a+b*c+(d*e+f)*g
+
stack
a
output
36
Ex: a+b * c+(d*e+f)*g
+
stack
a
output
b
37
Ex: a+b * c+(d*e+f)*g
a b +
*
stack
output
38
Ex: a+b*c+(d*e+f)*g
a b +
*
stack
output
c
39
Ex: a+b*c+ (d*e+f)*g
a b c
stack
output
*
*
+
40
Ex: a+b*c + (d*e+f)*g
a b c
stack
output
*
* +
41
Ex: a+b*c+(d*e+f)*g
a b c
stack
output
*
* + +
42
Ex: a+b*c+( d*e+f)*g
a b c * +
+ (
output stack
43
Ex: a+b*c+( d *e+f)*g
a b c * +
+ (
output stack
d
44
Ex: a+b*c+(d * e+f)*g
a b c * + d
output +
(
*
stack
45
Ex: a+b*c+(d* e +f)*g
a b c * + d
output +
(
*
stack
e
46
a b c * + d e
output +
(
stack
Ex: a+b*c+(d*e+f)*g *
47
a b c * + d e
output +
( +
stack
Ex: a+b*c+(d*e+f)*g *
48
a b c * + d e
output +
( +
+
stack
a b c * + d e *
output
Ex: a+b*c+(d*e+ f )*g *
f (
+
49
a b c * + d e
output +
( +
stack
+
stack
a b c * + d e *
output
Ex: a+b*c+(d*e+f ) *g *
f + (
50
+
stack
a b c * + d e *
output
Ex: a+b*c+(d*e+f ) *g f +
51
+
stack
a b c * + d e *
output
+
*
stack
a b c * + d e * f
+ output
Ex: a+b*c+(d*e+f) * g f +
52
+
stack
a b c * + d e *
output
+
*
stack
a b c * + d e * f
+ output
Ex: a+b*c+(d*e+f)* g f +
g
53
+
*
stack
a b c * + d e * f + g
output
a b c * + d e * f + g *
output stack
Ex: a+b*c+(d*e+f)*g
+
54
a b c * + d e * f + g * +
output stack
Therefore the postfix expression is a b c * + d e * f + g * + Ex: a+b*c+(d*e+f)*g
55
Question:-
Convert the following Infix expression
((A- (B+C))*D)$(E+F) into postfix notation.
56
Answer of previous Example: Given Infix notation is ((A- (B+C))*D)$(E+F)
SYMB POSTFIX STRING (OUTPUT) Stack
( (
( ( (
A A ( (
- A ( ( -
( A ( ( - (
B AB ( ( - (
+ AB ( ( - ( +
C ABC ( ( - ( +
) ABC+ ( ( -
) ABC+ - (
* ABC+ - ( *
D ABC+ - D ( *
) ABC+ - D *
$ ABC+ - D * $
( ABC+ - D * $ (
E ABC+ - D * E $ (
+ ABC+ -D * E $ ( +
F ABC+ -D * EF $ ( +
) ABC+ - D * EF + $
The output is ABC+ - D * EF + $ 57
Question : Consider the following Infix Expression and convert it into postfix expression
( A + B ) * ( C - D )
58
(2) Evaluating a postfix expression Using stack
59
Algorithm: Evaluation of Postfix Expression
1. Set P as Expression and add a right parenthesis “)” at the end of P, S as stack, and a Final Value.
2. Scan P from left to right and repeat step 3 to 5 till end of expression.
3. If an operand is encountered, put it on the stack S.
4. If operator is encountered
a) Pop top two elements from the stack where A is the top element and B is next top element
b) Evaluate B op A.
c) Push the result of above (b) back on the stack S.
(end of if)
(end of step 2 )
(End of step 2 loop)
5. Set Final Value equal to the top element of the stack S.
6. Exit.
60
(2) Evaluating a postfix expression
• Ex: 6 2 3 + - 3 8 2 / + * 2 $ 3 + is the given postfix expression.
• If operands, push in the stack.
• If operator , Pop two top operands from Stack and apply encountered operator on both operands and push result back to Stack.
6
61
(2) Evaluating a postfix expression
• Ex: 6 2 3 + - 3 8 2 / + * 2 $ 3 + is the given postfix expression.
6 2
62
(2) Evaluating a postfix expression
• Ex: 6 2 3 + - 3 8 2 / + * 2 $ 3 + is the given postfix expression.
6 2 3
63
(2) Evaluating a postfix expression
• Ex: 6 2 3 + - 3 8 2 / + * 2 $ 3 + is the given postfix expression.
6 2 3
6 5
64
(2) Evaluating a postfix expression
• Ex: 6 2 3 + - 3 8 2 / + * 2 $ 3 + is the given postfix expression.
6 5
1
65
(2) Evaluating a postfix expression
• Ex: 6 2 3 + - 3 8 2 / + * 2 $ 3 + is the given postfix expression.
1 3
66
(2) Evaluating a postfix expression
• Ex: 6 2 3 + - 3 8 2 / + * 2 $ 3 + is the given postfix expression.
1 3 8
67
(2) Evaluating a postfix expression
• Ex: 6 2 3 + - 3 8 2 / + * 2 $ 3 + is the given postfix expression.
1 3 8
2
68
(2) Evaluating a postfix expression
• Ex: 6 2 3 + - 3 8 2 / + * 2 $ 3 + is the given postfix expression.
1 3 8
2
1 3
4
69
(2) Evaluating a postfix expression
• Ex: 6 2 3 + - 3 8 2 / + * 2 $ 3 + is the given postfix expression.
1 3 8
2
1 3
4
1 7
70
(2) Evaluating a postfix expression
• Ex: 6 2 3 + - 3 8 2 / + * 2 $ 3 + is the given postfix expression.
1 3 8
2
1 3
4
1 7
7
71
(2) Evaluating a postfix expression
• Ex: 6 2 3 + - 3 8 2 / + * 2 $ 3 + is the given postfix expression.
7 2
49
72
(2) Evaluating a postfix expression
• Ex: 6 2 3 + - 3 8 2 / + * 2 $ 3 + is the given postfix expression.
7 2
49 49
3
73
(2) Evaluating a postfix expression
• Ex: 6 2 3 + - 3 8 2 / + * 2 $ 3 + is the given postfix expression.
7 2
49 49
3
52
74
Question: Evaluate the following Postfix expression 456*+
75
Infix to Prefix Conversion
Step 1: Reverse the infix expression i.e A+B*C will become C*B+A.
Note: while reversing each ‘(‘ will become ‘)’ and each ‘)’ becomes ‘(‘.
Step 2: Obtain the postfix expression of the modified expression i.e CB*A+.
Step 3: Reverse the postfix expression. Hence in our example prefix is +A*BC.
76
Question: Convert following infix expression to prefix
Expression = (A+B^C)*D+E^5 Ans : +*+A^BCD^E5
77
Algorithm of Infix to Prefix :
Step 1. Push “)” onto STACK, and add “(“ to end of the A
Step 2. Scan A from right to left and repeat step 3 to 6 for each element of A until the STACK is empty
Step 3. If an operand is encountered add it to B
Step 4. If a right parenthesis is encountered push it onto STACK Step 5. If an operator is encountered then:
a. Repeatedly pop from STACK and add to B each operator (on the top of STACK) which has same or higher precedence than the operator.
b. Add operator to STACK
Step 6. If left parenthesis is encountered then
a. Repeatedly pop from the STACK and add to B (each operator on top of stack until a left parenthesis is encountered)
b. Remove the left parenthesis
Step 7. Exit 78
Prefix to Infix conversion
Algorithm for Prefix to Infix:
•Read the Prefix expression in reverse order (from right to left)
•If the symbol is an operand, then push it onto the Stack
•If the symbol is an operator, then pop two operands from the Stack Create a string by concatenating the two operands and the operator between them.
string = (operand1 + operator + operand2) And push the resultant string back to Stack
•Repeat the above steps until end of Prefix expression.
79
Postfix to Infix conversion
Algorithm
1.While there are input symbol left
…1.1 Read the next symbol from the input.
2.If the symbol is an operand
…2.1 Push it onto the stack.
3.Otherwise,
…3.1 the symbol is an operator.
…3.2 Pop the top 2 values from the stack.
…3.3 Put the operator, with the values as arguments and form a string.
…3.4 Push the resulted string back to stack.
4.If there is only one value in the stack
…4.1 That value in the stack is the desired infix string.
80
Postfix to Infix Conversion Examples
81
82