/*
 * public void Hanoi(int n, String source, String dest, String free ) {
 * 	Marker 'A'
 * 	if (n > 0) {
 * 		Hanoi(n-1, source, free, dest);
 * 		Marker 'B'
 * 		MoveOne(source, dest);
 * 		Hanoi(n-1, free, dest, source);
 * 		Marker 'C'
 * 	}
 * }
 */
public class StackHanoi {

	private static class HanoiFrame {
		int n;
		String source, dest, free;
		char nextInstruction;
		int t1, t2;
		public HanoiFrame(int n, String source, String dest, String free, char next) {
			this.n = n;
			this.source = source;
			this.dest = dest;
			this.free = free;
			this.nextInstruction = next;
		}
	}
	
	public static void MoveOne(String source, String dest) {
		System.out.printf( "%s --> %s\n", source, dest);
	}
	
	static void stackHanoi(int n, String source, String dest, String free) {
		Stack<HanoiFrame> stack = new Stack<HanoiFrame>();
		char nextInstruction = 'A';
		stack.push( new HanoiFrame(n, source, dest, free, 'Z'));
		
		while (nextInstruction != 'Z') {
			HanoiFrame top = stack.top();
			if (nextInstruction == 'A') {
				if (top.n == 0) {
					nextInstruction = top.nextInstruction;
					stack.pop();
				}
				else {
					stack.push( new HanoiFrame(top.n-1, top.source, top.free, top.dest, 'B'));
					nextInstruction = 'A';
				}
			}
			else  if (nextInstruction == 'B') {
				MoveOne(top.source, top.dest);
				stack.push(new HanoiFrame(top.n-1, top.free, top.dest, top.source, 'C'));
				nextInstruction = 'A';
			}
			else if (nextInstruction == 'C') {
				nextInstruction = top.nextInstruction;
				stack.pop();
			}
		}
		
	}
	
	public static void main(String[] args) {
		stackHanoi(3, "A", "B", "C");
	}

}
