KEMBAR78
Stack Algorithm | PDF
StacksStacks
SyllabusSyllabus
 List&Arrays  Stacks ShortingList&Arrays
‐Consisting of a 
collection 
of elements
‐Allow insertions and 
removals only at 
top of stack(LIFO)
Shorting
‐Arranging data in 
some given order
of elements top of stack(LIFO)
Queue
All i ti t
•Searching
‐Finding the
Recursion
‐Allow insertions at 
the back and removals 
from the front  (FIFO)
Finding the 
location of a given 
item
‐Is the process of 
repeating items in 
a self‐similar way
Linked Lists Trees
Graphs and their 
Application Linked Lists 
‐Allow insertions and removals 
anywhere 
‐ High‐speed searching and 
sorting of data and efficient 
elimination of duplicate data 
items
OutlineOutline 
P i lPrevious class
What is Stack 
Examples
Push and pop 
Application 
Postfix
Infix, 
Prefixf
Tower of Hanoi Problem
Previous classPrevious class
List vs AarryList  vs Aarry
Sum=0
Sum of array  Sum of Matrices Product of Matrices
Int c[3,5] Sum=0
F (k 0 k 3 k )for (i=0;i<9;i++)
{
sum=sum+a[i]
[ ]
For(i=0;i<3;i++)
{
For(j=0;j<5;j++)
For(k=0;k<3;k++)
For(l=0;l<3;l++)
For(i=0;i<5;i++)
sum sum+a[l][i]*b[i][l]}
scanf(“%d”,sum)
{
c[i][j]=a[i][j]+b[i][j]
}
sum=sum+a[l][i]*b[i][l]
}
c[k][l]=sum
sum=0
4
}
sum=0
}
}
StacksStacks
– New nodes can be added and removed only at theNew nodes can be added and removed only at the 
top
Similar to a pile of dishes– Similar to a pile of dishes
– Last‐in, first‐out (LIFO) 
– Bottom of stack indicated by a link member to 
NULL
TOP
– Constrained version of a linked list
₋ TOP=‐1 means there is not item in 
h kthe stacks
Push and PopPush and Pop
push
– Adds a new node to the top of the stack
poppop
– Removes a node from the top 
– Stores the popped value 
– Returns true if pop was successful
Push and Pop(cont’d)Push and Pop(cont d)
Push  Push  Push  Push  Pop Push 
D D
E
Dtop
top
top
A
D
C
B
C
B
C
B
D
C
Btop
top
p
B
A
B
A
B
A A
B
Atop
top
A
top=0 top=1 Top=2 Top=3 Top=3top=4top=‐1
If top is greater than maximum capacity of stack push operationIf top is greater than maximum capacity of stack , push operation 
cannot be performed.
If top is lesser than 0, pop operation cannot be performed.
PushPush
Push(cont’d)Push(cont d)
Algorithm
Push(int data, int array, int top, int capacity)
{
Algorithm
{
if (top < capacity‐1)
top++top++
array[top]=data
lelse
output “out of space”
return top, array;
}
PopPop
POP(cont’d)POP(cont d)
Algorithm
pop(int array, int top):
{{
If (top>=0)
data=array[top]
top‐‐p
else
output “no elements in the stack”output  no elements in the stack
return top;
}
OutlineOutline 
P i lPrevious class
What is Stack 
ExamplesExamples
Push and pop 
ApplicationApplication 
Infix to Postfix
Postfix evaluationPostfix evaluation, 
Infix to Prefix
Prefix evaluationPrefix evaluation
Tower of Hanoi Problem
Application of StacksApplication of Stacks
More applications related to computer science
₋ Program execution stack
₋ Evaluating expressions
Application of StacksApplication of Stacks
Consider the arithmetic statement in the assignment 
statement:
x = a * b + c
Compiler must generateCompiler must generate 
machine instructions
1 LOAD a N t thi i "i fi " t tiN t thi i "i fi " t ti1. LOAD  a
2. MULT  b
Note: this is "infix" notation
The operators are between
the operands
Note: this is "infix" notation
The operators are between
the operands
3. ADD  c
4. STORE  x
the operandsthe operands
14
Infix to PostfixInfix to Postfix
Most compilers convert an expression in infix
notation to postfixp f
th t itt ft th d– the operators are written after the operands
So    a * b + c   becomes   a  b * c +
Ad tAdvantage:
– expressions can be written without parentheses
15
Infix to Postfix(cont’d)Infix to Postfix(cont d)
Example
INFIX POSTFIX  
A + B  A B +
p
A * B + C
A B * C +
A * (B + C) A B C + *
A ‐ (B ‐ (C ‐ D)) A B C D---
A ‐ B ‐ C ‐ D A B-C-D-
16
Infix to Postfix (cont’d)Infix to Postfix (cont d)
• It useful because evaluation of postfix is faster• It useful because evaluation of postfix is faster
•Humans usually apply the rules of precedence to•Humans usually apply the rules of precedence to 
set parentheses to determine the order of  
evaluation .evaluation .
•Then build the postfix expression starting with the e bu d e pos e p ess o s a g e
first operator.
• e.g., 1*2+3 = (1*2)+3 leads to postfix 12*3+
•How do we apply the rules of precedence?
Infix to Postfix (cont’d)Infix to Postfix (cont d)
•Example: 1*2+3
* ( ) d 12 ( fi )‐scan: *,+ (operators) and 12 (postfix)
d f * i hi h th th‐precedence of * is higher than +; thus, 
append * to postfix: + (ops ) and 12* (postfix)append * to postfix: + (ops.) and 12* (postfix)
scan further: + (ops ) and 12*3 (postfix)‐scan further: + (ops.) and 12*3 (postfix)
‐there are no further operators thus postfix is 12*3+‐there are no further operators, thus, postfix is 12 3+
Infix to Postfix (cont’d)Infix to Postfix (cont d)
Example: 1+2*3^4/5‐6Example: 1+2 3 4/5 6
scan: + * (operators) and 12 (postfix)‐scan: +,* (operators) and 12 (postfix)
‐precedence of + is lower than *; thus, 
‐scan  further: +,*,^ (operators) and 123 (postfix)
‐precedence of * is lower than ^; thus, 
‐scan further: +,*,^,/ (ops.) and 1234 (postfix)scan further: +, , ,/ (ops.) and 1234 (postfix)
‐precedence of ^ is higher than /; thus, 
append ^: +,*,/ (ops.) and 1234^ (postfix)
Infix to Postfix (cont’d)Infix to Postfix (cont d)
Example: 1+2*3^4/5‐6p
‐currently: + * / (ops ) and 1234^ (postfix)currently: +, ,/ (ops.) and 1234  (postfix)
‐"precedence" of * is higher than /; thus, 
‐append *: +,/ (ops.) and 1234^* (postfix)
d f i l th / th‐precedence of + is lower than /; thus, 
‐scan further: +,/,‐ (ops.) and 1234^*5 (postfix), , ( p ) (p )
‐precedence of / is higher than ‐; thus, 
‐append  /: +,‐ (ops.) and 1234^*5/ (postfix)
Infix to Postfix (cont’d)Infix to Postfix (cont d)
Example: 1+2*3^4/5‐6
‐currently: +,‐ (ops.) and 1234^*5/ (postfix)
‐"precedence" of + is higher than ‐; thus, 
‐append +: ‐ (ops.) and 1234^*5/+ (postfix)append +:  (ops.) and 1234 5/+ (postfix)
‐scan: ‐ (ops.) and 1234^*5/+6 (postfix)
‐no more operators: 1234^*5/+6‐ (postfix)
Infix to Postfix (cont’d)Infix to Postfix (cont d)
operator_stack = empty stack
h l ( NULL)
Algorithm:
while (input!=NULL)
{
symbol = next input
g
if (symbol ==operand)
postfix string= symbol
else
while (top>=0&& operator_stack (top)> symbol)
{
postfix string= pop(operator stack)postfix string pop(operator_stack)
}
push (operator_stack, symbol )
}}
while (operator_stack not empty)
{
fi i ( k)postfix string= pop(operator_stack)
}
Postfix Evaluation
Evaluating postfix Expressions
Postfix Evaluation
1. Scan the expression from left to right to find an operator.
2 L t (" d li ") th l t t di d2. Locate ("underline") the last two preceding operands 
and combine them using this operator. 
3 Repeat until the end of the expression is reached3. Repeat until the end of the expression is reached.
Example:
2 7 5 6 *
2 3 4 + 5 6 - - *
 2 3 4 + 5 6 - - *
 2 7 5 6 - - *
 2 7 5 6 - - *
 2 7 -1 - *
23
 2 7 1
 2 7 -1 - *  2 8 *  2 8 *  16
Postfix Evaluation(cont’d)Postfix Evaluation(cont d)
Evaluating postfix Expressions
Example: 623+‐382/+*2^3+
Evaluating postfix Expressions
‐scan from left to right: 6,2,3,+
l t 2 d 3 6 5‐apply + to 2 and 3: 6,5
‐scan further: 6,5,‐
l t 6 d 5 1‐apply ‐ to 6 and 5: 1
‐scan further: 1,3,8,2,/
l / t 8 d 2 1 3 4‐apply / to 8 and 2: 1,3,4
‐scan further: 1,3,4,+
Postfix Evaluation(cont’d)Postfix Evaluation(cont d)
Evaluating postfix Expressions
Example.: 623+‐382/+*2^3+,
currently: 1,3,4,+ 
‐apply + to 3 and 4: 1,7
‐scan further: 1,7,*
‐apply * to 1 and 7: 7
‐scan further: 7,2,^
‐apply ^ to 7 and 2: 49
‐scan further: 49,3,+
‐apply + to 49 and 3: 52
Postfix Evaluation(cont’d)
Postfix String: 1 2 3 * + 4 ‐ .
Initially the Stack is empty. Now, the first three characters scanned are 1,2 and 3, which are operands. Thus 
h ll b h d h k h dthey will be pushed into the stack in that order. 
Stack Expression
Next character scanned is "*", which is an operator. Thus, we pop the top two elements from the stack and 
perform the "*" operation with the two operands. The second operand will be the first element that is 
popped.popped. 
The value of the expression(2*3) that has been evaluated(6) is pushed into the stack.
Stack Expression
Stack Expression
Next character scanned is "+", which is an operator. Thus, we pop the top two elements from the stack and 
perform the "+" operation with the two operands. The second operand will be the first element that is 
popped. 
Stack Expression
The value of the expression(1+6) that has been evaluated(7) is pushed into the stack. 
Next character scanned is "4", which is added to the stack.
Stack Expression
Stack Expression
Next character scanned is "‐", which is an operator. Thus, we pop the top two elements from the stack and 
perform the "‐" operation with the two operands. The second operand will be the first element that is 
popped. 
The value of the expression(7‐4) that has been evaluated(3) is pushed into the stack.
Stack ExpressionStack Expression
The value of the expression(7‐4) that has been evaluated(3) is pushed into the stack.
Stack Expression
Now, since all the characters are scanned, the remaining element in the stack (there will be only one 
element in the stack) will be returned.    
E d ltEnd result: 
Postfix String : 1 2 3 * + 4 ‐
Result : 3
Postfix(cont’d)Postfix(cont d)
Algorithm
operand_stack = empty stack
while (input!=NULL)
Algorithm:
while (input! NULL)
{
symbol = next input symbol
if (symbol ==operand)
push(operand_stack, symbol)
elseelse
operand2 = pop(operand_stack)
operand1 = pop(operand stack)p d p p( p d_ t k)
result = apply symbol to operand1 and operand2
push(operand_stack, result)
pop(operand_stack)
}
Infix to PrefixInfix to Prefix
INFIX PREFIX
A + B  + A B
A * B + C + * A B C
A * (B + C)  * A + B C
A ‐ (B ‐ (C ‐ D))  -A-B-C D
A ‐ B ‐ C ‐ D ---A B C D
fi b ffi b f
30
Prefix : Operators come before
the operands
Prefix : Operators come before
the operands
Infix to prefix conversionInfix to prefix conversion
Show me the algorithm in next classShow me the algorithm in next class
31
Prefix EvaluationPrefix Evaluation
Example: Infix: 1 * (2 + 3); Prefix: *1 + 2 3Example:  Infix: 1   (2 + 3); Prefix:  1 + 2 3
Reverse string: 32+1*g
in stack 3 ;  in string 2+1*
in stack 32; in string +1*g
scan +; in string  1*
Result= 2 + 3
in stack 5; in string 1*
in stack 51; in string*;
Scan *
Result=1*5
in stack 5
Prefix Evaluation(cont’d)Prefix Evaluation(cont d)
Rev_pref=Reverse(prefix)
Symbol=Rev_pref
scan the reversed prefix expression;
hil ( b ! NULL)while(symbo !=NULL)
{
if (symbol operand )if (symbol==operand )
Stack_s=push(symbol)
elseelse
operand2=pop(top)
operand1 =pop(top)operand1 pop(top)
result = operand2 op operand1;
Stack_s=push( result)_ p ( )
}
return Stack_s(top)
The Tower of Hanoi ProblemThe Tower of Hanoi Problem
GIVEN: three poles– GIVEN: three poles
– a set of discs on the first pole, discs of different sizes, the smallest 
discs at the top
– GOAL: move all the discs from the left pole to the right one. 
– CONDITIONS: only one disc may be moved at a time. 
A di b l d ith t l t f l– A disc can be placed either on an empty pole or on top of a larger 
disc. 
Towers of HanoiTowers of Hanoi
Towers of HanoiTowers of Hanoi
Towers of HanoiTowers of Hanoi
Towers of HanoiTowers of Hanoi
Top of 1st place is moved to 2nd place by help of 3rd place
Towers of HanoiTowers of Hanoi
Towers of HanoiTowers of Hanoi
Towers of HanoiTowers of Hanoi
Towers of HanoiTowers of Hanoi
Top of 2nd place is moved to 3rd place by help of 1st place
ProblemProblem
DD
C
B
A
43
Towers of Hanoi: AlgorithmTowers of Hanoi: Algorithm
Input number of disksInput number of disks
If (n==1)
move single disk from peg A(1st) to peg C(3rd) and stopmove single disk from peg A(1 ) to peg C(3 ) and stop.
else
move the top (n‐1) disks from peg A to peg B using peg C as
auxiliary.auxiliary.
Move remaining disks from peg A to peg CMove remaining disks from peg A to peg C.
Move (n 1) disks from peg B to peg C using peg A asMove (n‐1) disks from peg B to peg C using peg A as
auxiliary.

Stack Algorithm