Monday, March 28, 2016

Tower of Hanoi

import java.util.Stack;

public class TowerOfHanoi {

static int parseIndex = 1;

public static void main(String[] args) {
Stack<Integer> sourceTower = new Stack<>();
Stack<Integer> destinationTower = new Stack<>();
Stack<Integer> bufferTower = new Stack<>();
int n = 3;

for (int index = n; index > 0; index--)
sourceTower.add(index);

System.out.println("---before moving---");
System.out.println("sourceTower");
printStack(sourceTower);
System.out.println("destinationTower");
printStack(destinationTower);

moveDisks(n, sourceTower, destinationTower, bufferTower);

System.out.println("---after moving---");
System.out.println("sourceTower");
printStack(sourceTower);
System.out.println("destinationTower");
printStack(destinationTower);
}

public static void printStack(Stack<Integer> sourceTower) {
System.out.println(sourceTower.toString());
}

private static void moveDisks(int n, Stack<Integer> sourceTower, Stack<Integer> destinationTower,
Stack<Integer> bufferTower) {
if (n <= 0)
return;

moveDisks(n - 1, sourceTower, bufferTower, destinationTower);
System.out.println("----parse-----" + parseIndex++);
printStack(sourceTower);
printStack(destinationTower);
printStack(bufferTower);
moveTopDisc(sourceTower, destinationTower);
moveDisks(n - 1, bufferTower, destinationTower, sourceTower);
}

private static void moveTopDisc(Stack<Integer> sourceTower, Stack<Integer> destinationTower) {
int lastItem = sourceTower.pop();
destinationTower.add(lastItem);
}
}

No comments:

Post a Comment