Applications of Stack
Applications of Stack
Validity of expression
Valid Expression Rules:
1) There should not be 2 consecutive OPRANDS
2) There should not be 2 consecutive OPERATORS.
3) Operand must not be followed by opening parenthesis.
4) Opening parenthesis must not be followed by operator.
5) Operator must not be followed by closing parenthesis.
6) Closing parenthesis must not be followed by operator.
7) Last symbol should not be an operator.
If any of the above condition is become true then expression is not a valid expression.
For validity of parenthesis consider following rules:
1) Same number of closing and opening brackets.
2) Sequence of opening and closing brackets.
Pseudo code:
while (not end of input)
symbol = input symbol
if (symbol is operand)
push (operand_stack, symbol)
else
operand2 = pop(operand_stack)
operand1 = pop(operand_stack)
result = apply operation specified by symbol on operand1 and operand2
push (operand_stack, result)
return pop(operand_stack)
Example:
Postfix expression : 6 2 3 + - 3 8 2 / + * 2 ^ 3 +
Answer is: 52
Answer: 52
Towers of Hanoi
The Tower of Hanoi is a mathematical game or puzzle. It consists of three towers- source,
axillary and destination. There are N disks of decreasing size (no two disks are of the same
size). Initially all the disks are stacked on the source tower in their decreasing order of size.
The objective of the puzzle is to move all the disks from source tower to the destination tower
with the help of intermediate tower. There are 2 rules of the puzzle:
1) Only one disk can be moved at a time.
2) Bigger disk cannot be placed on the smaller disk.
Consider three towers name A, B and C. A is source tower, C is Destination tower and B is
intermediate tower. So, we want to transfer N disks from tower A to tower C using tower B.
We will perform following Steps to get solution:
1) Move N-1 discs from A to B using C.
2) Move discs N from A to C.
3) Move N-1 discs from B to C using A.
Algorithm:
function move (N, source, intermediate, destination)
If N >0 then
move (N-1, source, destination, intermediate)
place Nth disk from source to destination
move (N-1, intermediate, source, destination)
end if
Working of algorithm:
Consider N=3 and see how algorithm works with recursion
Illustration:
1) N=3
2) N=4