Stack
A linear list which allows insertion and deletion of an element at one end only is called stack.
The insertion operation is called as PUSH and deletion operation as POP.
The most accessible elements in stack is known as top.
The elements can only be removed in the opposite orders from that in which they were added to
the stack.
Such a linear list is referred to as a LIFO (Last In First Out) list.
Deletion
Insertion
C
B … …
A
TOP
#3130702 (DS) Unit 2 – Linear Data Structure (Stack) 1
Stack Cont…
A pointer TOP keeps track of the top element in the stack.
Initially, when the stack is empty, TOP has a value of “zero”.
Each time a new element is inserted in the stack, the pointer is incremented by “one” before,
the element is placed on the stack.
The pointer is decremented by “one” each time a deletion is made from the stack.
#3130702 (DS) Unit 2 – Linear Data Structure (Stack) 2
Applications of Stack
Recursion
Keeping track of function calls
Evaluation of expressions
Reversing characters
Servicing hardware interrupts
Solving combinatorial problems using backtracking
Expression Conversion (Infix to Postfix, Infix to Prefix)
Game Playing (Chess)
Microsoft Word (Undo / Redo)
Compiler – Parsing syntax & expression
Finding paths
#3130702 (DS) Unit 2 – Linear Data Structure (Stack) 3
Procedure : PUSH (S, TOP, X)
This procedure inserts an element X to the top of a stack.
Stack is represented by a vector S containing N elements.
A pointer TOP represents the top element in the stack.
1. [Check for stack overflow] Stack is empty, TOP = 0, N=3 TOP = 3 -5
If TOP ≥ N TOP = 2 8
Then write (‘STACK OVERFLOW’) PUSH(S, TOP, 10) TOP = 1 10
Return S
2. [Increment TOP] PUSH(S, TOP, 8)
TOP ← TOP + 1
PUSH(S, TOP, -5)
3. [Insert Element]
S[TOP] ← X
PUSH(S, TOP, 6)
4. [Finished]
Return Overflow
#3130702 (DS) Unit 2 – Linear Data Structure (Stack) 4
Function : POP (S, TOP)
This function removes & returns the top element from a stack.
Stack is represented by a vector S containing N elements.
A pointer TOP represents the top element in the stack.
1. [Check for stack underflow] POP(S, TOP) TOP = 3 -5
TOP = 2 8
If TOP = 0
TOP = 1 10
Then write (‘STACK UNDERFLOW’) POP(S, TOP)
TOP = 0 S
Return (0)
2. [Decrement TOP] POP(S, TOP)
TOP ← TOP - 1
3. [Return former top element of POP(S, TOP)
stack]
Return(S[TOP + 1])
Underflow
#3130702 (DS) Unit 2 – Linear Data Structure (Stack) 5
Function : PEEP (S, TOP, I)
This function returns the value of the Ith element from the TOP of the stack. The element is not
deleted by this function.
Stack is represented by a vector S containing N elements.
1. [Check for stack underflow] PEEP (S, TOP, 2) TOP = 3 -5
8
If TOP-I+1 ≤ 0
10
Then write (‘STACK UNDERFLOW’) PEEP (S, TOP, 3)
S
Return (0)
2. [Return Ith element from top PEEP (S, TOP, 4)
of the stack]
Return(S[TOP–I+1]) Underflow
#3130702 (DS) Unit 2 – Linear Data Structure (Stack) 6
PROCEDURE : CHANGE (S, TOP, X, I)
This procedure changes the value of the Ith element from the top of the stack to X.
Stack is represented by a vector S containing N elements.
1. [Check for stack underflow] CHANGE (S, TOP, 50, 2) TOP = 3 -5
8
50
If TOP-I+1 ≤ 0
10
9
Then write (‘STACK UNDERFLOW’)
CHANGE (S, TOP, 9, 3) S
Return
2. [Change Ith element from top
of the stack] CHANGE (S, TOP, 25, 8)
S[TOP–I+1] ← X
3. [Finished]
Underflow
Return
#3130702 (DS) Unit 2 – Linear Data Structure (Stack) 7
Polish Expression & their Compilation
Evaluating Infix Expression
a+b*c+d*e
1 2
3
4
A repeated scanning from left to right is needed as operators appears inside the operands.
Repeated scanning is avoided if the infix expression is first converted to an equivalent
parenthesis free prefix or suffix (postfix) expression.
Prefix Expression: Operator, Operand, Operand
Postfix Expression: Operand, Operand, Operator
#3130702 (DS) Unit 2 – Linear Data Structure (Stack) 8
Polish Notation
This type of notation is known Lukasiewicz Notation or Polish Notation or Reverse Polish
Notation due to Polish logician Jan Lukasiewicz.
In both prefix and postfix equivalents of an infix expression, the variables are in same relative
position.
The expressions in postfix or prefix form are parenthesis free and operators are rearranged
according to rules of precedence for operators.
#3130702 (DS) Unit 2 – Linear Data Structure (Stack) 9
Polish Notation
Sr. Infix Postfix Prefix
1 a a a
2 a+b ab+ +ab
3 a+b+c ab+c+ ++abc
4 abc++ +a+bc
a + (b + c)
abc*+ +a * b c
5 a + (b * c)
abc+* *a+bc
6 a * (b + c)
a b *c* ** a b c
7 a*b*c
a+b+c a+b+c (ab+)+ c (ab+) c + ab+c+
#3130702 (DS) Unit 2 – Linear Data Structure (Stack) 10
Finding Rank of any Expression
E = ( A + B * C / D - E + F / G / ( H + I ))
Note: R = Rank, Rank of Variable = 1, Rank of binary operators = -1
Rank (E) = R(A) + R(+) + R(B) + R(*) + R(C) + R (/) + R(D) + R(-) + R(E) + R(+) + R(F) + R(/) + R(G)
+ R(/) + R(H) + R(+) + R(I)
Rank (E) = 1 + (-1) + 1 + (-1) + 1 + (-1) + 1 + (-1) + 1 + (-1) + 1 + (-1) + 1 + (-1) + 1 + (-1) + 1
Rank (E) = 1
Any Expression is valid if Rank of that expression is 1
#3130702 (DS) Unit 2 – Linear Data Structure (Stack) 11
Convert Infix to Postfix Expression
Symbol Input precedence Stack precedence Rank function (R)
function (F) function (G)
+, - 1 2 -1
*, / 3 4 -1
^ 6 5 -1
Variables 7 8 1
( 9 0 -
) 0 - -
#3130702 (DS) Unit 2 – Linear Data Structure (Stack) 12
Algorithm : REVPOL
Given an input string INFIX containing an infix expression which has been padded on the right
with ‘)’.
This algorithm converts INFIX into reverse polish and places the result in the string POLISH.
All symbols have precedence value given by the table.
Stack is represented by a vector S, TOP denotes the top of the stack, algorithm PUSH and POP
are used for stack manipulation.
Function NEXTCHAR returns the next symbol in given input string.
The integer variable RANK contains the rank of expression.
The string variable TEMP is used for temporary storage purpose.
#3130702 (DS) Unit 2 – Linear Data Structure (Stack) 13
1. [Initialize Stack] 5. [Remove symbols with greater precedence
TOP 1 from stack]
S[TOP] ← ‘(’ IF TOP < 1
Then write (‘INVALID’)
2. [Initialize output string and rank count]
EXIT
POLISH ‘’
Repeat while G(S[TOP]) > F(NEXT)
RANK 0
TEMP POP (S, TOP)
3. [Get first input symbol] POLISH POLISH O TEMP
NEXT NEXTCHAR(INFIX) RANK RANK + R(TEMP)
4. [Translate the infix expression] IF RANK <1
Repeat thru step 7 Then write (‘INVALID’)
while NEXT != ‘ ‘ EXIT
6. [Are there matching parentheses]
Symbol IPF (F) SPF (G) RF (R) IF G(S[TOP]) != F(NEXT)
+, - 1 2 -1 Then call PUSH (S,TOP, NEXT)
Else POP (S,TOP)
*, / 3 4 -1
7. [Get next symbol]
^ 6 5 -1 NEXT NEXTCHAR(INFIX)
Variables 7 8 1 8. [Is the expression valid]
IF TOP != 0 OR RANK != 1
( 9 0 - Then write (‘INVALID‘)
) 0 - - Else write (‘VALID’)
#3130702 (DS) Unit 2 – Linear Data Structure (Stack) 14
Input Content of Reverse polish expression Rank
(a+b^c^d)*(e+f/d)) Symbol stack
( 0
NEXT (
1. [Initialize Stack]
TOP 1
S[TOP] ← ‘(’
2. [Initialize output string and rank count]
POLISH ‘’
RANK 0
3. [Get first input symbol]
NEXT NEXTCHAR(INFIX)
#3130702 (DS) Unit 2 – Linear Data Structure (Stack) 15
Input Content of Reverse polish Rank
(a+b^c^d)*(e+f/d)) Symbol stack expression
( 0
NEXT ( 0
((
4. [Translate the infix expression]
Repeat thru step 7 a ((a 0
while NEXT!= ‘ ‘ + ((+
(( a 1
5. [Remove symbols with greater precedence from b ((+b a 1
stack] ((+
((+^ ab 2
^
IF TOP < 1
c ((+^c ab 2
Then write (‘INVALID’)
EXIT ^ ((+^^
((+^ abc 3
Repeat while G(S[TOP]) > F(NEXT) d ((+^^d abc 3
TEMP POP (S, TOP)
POLISH POLISH O TEMP ) ((( abcd^^+ 1
RANK RANK + R(TEMP)
IF RANK <1
Then write (‘INVALID’)
EXIT
6. [Are there matching parentheses]
IF G(S[TOP]) != F(NEXT)
Then call PUSH (S,TOP, NEXT)
Else POP (S,TOP)
7. [Get next symbol]
NEXT NEXTCHAR(INFIX)
#3130702 (DS) Unit 2 – Linear Data Structure (Stack) 16
Perform following operations
Convert the following infix expression to postfix. Show the stack contents.
A$B-C*D+E$F/G
A+B–C*D*E$F$G
a+b*c-d/e*h
((a+b^c^d)*(e+f/d))
Convert the following infix expression to prefix.
A+B–C*D*E$F$G
#3130702 (DS) Unit 2 – Linear Data Structure (Stack) 17
General Infix-to-Postfix Conversion
Create an empty stack called stack for keeping operators. Create an empty list for output.
Read the character list from left to right and perform following steps
1 If the character is an operand (Variable), append it to the end of the output list
2 If the character is a left parenthesis ‘(’, push it on the stack
3 If the character is a right parenthesis ‘)’, pop the stack until the corresponding left parenthesis ‘)’ is
removed. Append each operator to the end of the output list.
4 If the token is an operator, *, /, +, or -, push it on the stack. However, first remove any operators already on
the stack that have higher or equal precedence and append them to the output list.
(a+b^c^d)*(e+f/d)
#3130702 (DS) Unit 2 – Linear Data Structure (Stack) 18
Evaluation of postfix expression
Each operator in postfix string refers to the previous two operands in the string.
Each time we read an operand, we PUSH it onto Stack.
When we reach an operator, its operands will be top two elements on the stack.
We can then POP these two elements, perform the indicated operation on them and PUSH the
result on the stack so that it will available for use as an operand for the next operator.
#3130702 (DS) Unit 2 – Linear Data Structure (Stack) 19
Evaluation of postfix expression
Evaluate Expression: 5 6 2 - +
Empty Stack
Read – , is it operator? POP
Read 5, is it operand? PUSH two symbols and perform
Read 6, is it operand? PUSH 2 operation and PUSH result
Read 2, is it operand? PUSH 6 4
5 Operand 1 – Operand 2 5
Read + , is it operator? POP
Read next symbol, if it two symbols and perform
is end of string, POP operation and PUSH result
answer from Stack
Answer 9 Operand 1 + Operand 2
#3130702 (DS) Unit 2 – Linear Data Structure (Stack) 20
Algorithm: EVALUATE_POSTFIX
Given an input string POSTFIX representing postfix expression.
This algorithm evaluates postfix expression and put the result into variable VALUE.
Stack is represented by a vector S, TOP denotes the top of the stack, Algorithm PUSH and POP
are used for stack manipulation.
Function NEXTCHAR returns the next symbol in given input string.
OPERAND1, OPERAND2 and TEMP are used for temporary variables
PERFORM_OPERATION is a function which performs required operation on OPERAND1 &
OPERAND2.
#3130702 (DS) Unit 2 – Linear Data Structure (Stack) 21
Algorithm: EVALUATE_POSTFIX
1. [Initialize Stack]
TOP 0
VALUE 0
2. [Evaluate the postfix expression]
Repeat until last character
TEMP NEXTCHAR (POSTFIX)
If TEMP is DIGIT
Then PUSH (S, TOP, TEMP)
Else OPERAND2 POP (S, TOP)
OPERAND1 POP (S, TOP)
VALUE PERFORM_OPERATION(OPERAND1, OPERAND2, TEMP)
PUSH (S, POP, VALUE)
3. [Return answer from stack]
Return (POP (S, TOP))
#3130702 (DS) Unit 2 – Linear Data Structure (Stack) 22
Evaluation of postfix expression
Evaluate Expression: 5 4 6 + * 4 9 3 / + *
Evaluate Expression: 7 5 2 + * 4 1 1 + / -
Evaluate Expression: 12, 7, 3, -, /, 2, 1, 5, +, *, +
#3130702 (DS) Unit 2 – Linear Data Structure (Stack) 23
Algorithm: EVALUATE_PREFIX
Given an input string PREFIX representing prefix expression.
This algorithm evaluates prefix expression and put the result into variable VALUE.
Stack is represented by a vector S, TOP denotes the top of the stack, Algorithm PUSH and POP
are used for stack manipulation.
Function NEXTCHAR returns the next symbol in given input string.
OPERAND1, OPERAND2 and TEMP are used for temporary variables
PERFORM_OPERATION is a function which performs required operation on OPERAND1 &
OPERAND2.
#3130702 (DS) Unit 2 – Linear Data Structure (Stack) 24
Algorithm: EVALUATE_PREFIX
1. [Initialize Stack]
TOP 0
VALUE 0
2. [Evaluate the prefix expression]
Repeat from last character up to first
TEMP NEXTCHAR (PREFIX)
If TEMP is DIGIT
Then PUSH (S, TOP, TEMP)
Else OPERAND1 POP (S, TOP)
OPERAND2 POP (S, TOP)
VALUE PERFORM_OPERATION(OPERAND1, OPERAND2, TEMP)
PUSH (S, POP, VALUE)
3. [Return answer from stack]
Return (POP (S, TOP))
#3130702 (DS) Unit 2 – Linear Data Structure (Stack) 25
Recursion
A procedure that contains a procedure call to itself or a procedure call to second procedure
which eventually causes the first procedure to be called is known as recursive procedure.
Two important conditions for any recursive procedure
1 Each time a procedure calls itself it must be nearer in some sense to a solution.
2 There must be a decision criterion for stopping the process or computation.
Two types of recursion
Primitive Recursion Non-Primitive Recursion
This is recursive defined function. This is recursive use of procedure.
E.g. Factorial function E.g. Find GCD of given two numbers
#3130702 (DS) Unit 2 – Linear Data Structure (Stack) 26
Algorithm to find factorial using recursion
Given integer number N
This algorithm computes factorial of N.
Stack S is used to store an activation record associated with each recursive call.
TOP is a pointer to the top element of stack S.
Each activation record contains the current value of N and the current return address
RET_ADDE.
TEMP_REC is also a record which contains two variables PARAM & ADDRESS.
Initially return address is set to the main calling address. PARAM is set to initial value N.
#3130702 (DS) Unit 2 – Linear Data Structure (Stack) 27
Algorithm: FACTORIAL
1. [Save N and return Address]
CALL PUSH (S, TOP, TEMP_REC)
2. [Is the base criterion found?]
If N=0
then FACTORIAL 1
GO TO Step 4
Else PARAM N-1
ADDRESS Step 3
GO TO Step 1
3. [Calculate N!]
FACTORIAL N * FACTORIAL
4. [Restore previous N and return address]
TEMP_REC POP(S,TOP)
(i.e. PARAM N, ADDRESS RET_ADDR)
GO TO ADDRESS
#3130702 (DS) Unit 2 – Linear Data Structure (Stack) 28
Trace of Algorithm FACTORIAL, N=2
Level Number Description Stack Content
Enter Level 1 Step 1: PUSH (S,0,(N=2, main address)) 2
(main call) Step 2: N!=0 Main
PARAM N-1 (1), ADDR Step 3 Address
TOP
Enter Level 2 Step 1: PUSH (S,1,(N=1, step 3)) 2 1
(first recursive Step 2: N!=0 Main Step
call) PARAM N-1 (3), ADDR Step 3 Address 3
TOP
Enter Level 3 Step 1: PUSH (S,2,(N=0, step 3)) 2 1 0
(second recursive Step 2: N=0 Main Step Step
call) FACTORIAL 1 Address 3 3
TOP
Step 4: POP(A,3)
GO TO Step 3 2 1
Main Step
Address 3
TOP
#3130702 (DS) Unit 2 – Linear Data Structure (Stack) 29
Trace of Algorithm FACTORIAL, N=2
Level Number Description Stack Content
Step 3: FACTORIAL 1*1 2
Return to Main
Level 2 Step 4: POP (A,2) Address
GO TO Step 3
TOP
Return to Step 3: FACTORIAL 2*1
Level 1
Step 4: POP (A,1)
GO TO Main Address TOP = 0
#3130702 (DS) Unit 2 – Linear Data Structure (Stack) 30