instagram

Tower of Hanoi in Java

This is very famous algorithm tower of hanoi

package com.omt.learn.algo;

import java.util.Stack;

public class HanoiTower {

	public static void main(String args[]) {
		Stack<Integer> towerOne = new Stack<>();

		for (int i = 5; i > 0; i--) {
			towerOne.push(i);
		}

		Stack<Integer> towerTwo = new Stack<>();
		Stack<Integer> towerThree = new Stack<>();

		towerOfHanoi(towerOne.size(), towerOne, towerTwo, towerThree);

		while (!towerThree.isEmpty()) {
			System.out.println(towerThree.pop());
		}

	}

	public static void towerOfHanoi(int n, Stack<Integer> towerOne, Stack<Integer> towerTwo,
			Stack<Integer> towerThree) {

		if (n > 0) {
			towerOfHanoi(n - 1, towerOne, towerThree, towerTwo);
			towerThree.push(towerOne.pop());
			towerOfHanoi(n - 1, towerTwo, towerOne, towerThree);
		}

	}

}
Share