Showing posts with label stack. Show all posts
Showing posts with label stack. Show all posts

Saturday, 12 October 2013

Infix to Postfix using Stack

Step1 : Push the delimiter “#” onto the stack.
Step2 : Read the characters one by one from the given infix expression
  1. If the character is an operand ,place it on to the output.
  2. If the character(ch) is equal to an operator or any opening symbol,then pop a character (pch)from the stack.If the stack priority of pch >= infix priority of ch ,then put pch in the output and push th ch into stack,if the condition didn‟t get satisfied then push pch and c into the stack.
  3. If the character is a closing symbol,pop all the operators from the stack till it encounters its corresponding opening symbol and place it on the output and discard both the opening and closing symbols.
Step3 : Repeat all the steps till # is encountered

Towers of Hanoi Using Stack (Recursive Solution)

(The problem is moving a collection of N disks of decreasing size from one pillar to another.The movement of the disks is restricted by the following rules:
Rule1: Only 1 disk could be moved at a time.
Rule2: No larger disk could ever reside on a pillar on top of a smaller disk.
Rule3: A 3rd pillar can be used as an intermediate to store one or more disks,while the disks are moved from source to destination )

Let N represent the number of disks
Step1: If N=1,move the disk from A to C.
Step2:
  1. If N=2,move the 1st disk from A to B,
  2. Then move the 2nd disk from A to C,
  3. Then move the 1st disk in B to C.
Step3: If N=3,repeat step2,to move the first two disks from A to B using C as intermediate.
Then move 3rd disk from A to C.Then repeat the step2 to move 2disks from B to C using A as intermediate

In general,to move N disks,apply recursive technique to move (N-1) disks from A to B with C as an intermediate.Then move the Nth disk from A to C.Then again apply the recursive technique to move (N-1) from B to C using A as intermediate.