Java towers of hanoi stack implementation

Examples

package com.w3spoint;
 
public class Test {
    private static Test[] tower; 
    private int stackSize;
    private int[] stackArray;
    private int top;
 
    /**
     * constructor to create stack with size
     * @param size
     */
    public Test(int size) {
        this.stackSize = size;
        this.stackArray = new int[stackSize];
        this.top = -1;
    }
 
    /**
     * Adds new entry to the top of the stack
     * @param entry
     * @throws Exception 
     */
    public void push(int entry) throws Exception {
    	this.stackArray[++top] = entry;
    }
 
    /**
     * Removes an entry from the top of the stack.
     * @return
     * @throws Exception 
     */
    public int pop() throws Exception {
        if(this.isStackEmpty()){
        	System.out.println("Stack underflow.");
        }
        return this.stackArray[top--];
    }
 
    /**
     * Returns top of the stack without removing it.
     * @return
     */
    public int peek() {
        return stackArray[top];
    }
 
    /**
     * Returns true if the stack is empty
     * @return
     */
    public boolean isStackEmpty() {
        return (top == -1);
    }
 
    /**
     * Returns true if the stack is full
     * @return
     */
    public boolean isStackFull() {
        return (top == stackSize - 1);
    }
 
    public void towersOfHanoi(int n) throws Exception {    	 
        //Create three stacks, tower[0] is scratch
        tower = new Test[4];
        for (int i = 0; i <= 3; i++){
            tower[i] = new Test(4);
        }
        for (int d = n; d > 0; d--){
            //Initialize and add disk d to tower 1
            tower[1].push(new Integer(d)); 
        }
        //Move n disks from tower 1 to 2 using 3 as intermediate tower
        showTowerStates(n, 1, 2, 3);
    }
 
    public void showTowerStates(int n, int x, int y, int z) {         
        if (n > 0) {
            try{
                showTowerStates(n - 1, x, z, y);
                //Move d from top of tower x to top of tower 
                Integer d = (Integer) tower[x].pop(); 
                tower[y].push(d); 
                System.out.println("Move disk " + d 
                        + " from tower "+ x + " to top of tower " + y);
                showTowerStates(n - 1, z, y, x);
            } catch(Exception e){
            	e.printStackTrace();
            }
        }
    }
 
	public static void main(String args[]){
		try {
			Test test = new Test(10);
			test.towersOfHanoi(3);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}

Output

Move disk 1 from tower 1 to top of tower 2
Move disk 2 from tower 1 to top of tower 3
Move disk 1 from tower 2 to top of tower 3
Move disk 3 from tower 1 to top of tower 2
Move disk 1 from tower 3 to top of tower 1
Move disk 2 from tower 3 to top of tower 2
Move disk 1 from tower 1 to top of tower 2
Content Protection by DMCA.com
Please Share