I already got the Towers of Hanoi with recursion, it's also working without any problems. But now I'd like to know how it could work without recursion but with stack instead.
public class Hanoirecursive {
static void move (
int x,
char start,
char help,
char aim) {
if (x == 1)
System.out.println(" from " + start + " to " + aim);
else {
move(x-1,start, aim, help);
System.out.println(" from " + start + " to " + aim);
move(x-1,help, start, aim);
}
}
public static void main (String args[]) {
int x = Integer.parseInt(args[0]);
if (x > 0) {
System.out.println("Movements: ");
move(x,'A','B','C');
}
else
System.out.println("No negative number.");
}
}
I would like to.. convert this code so it works with a stack and no longer with recursion but I really don't know where to start. Could you give me some hints please?
For the stack I could find this on the internet:
public class Stack {
private int[] stackElements;
private int top;
public Stack(int a) {
stackElements = new int[a];
top = -1;
}
public boolean isEmpty() {
return top == -1;
}
public void push(int b) {
stackElements[++top] = b;
}
public int pop() {
if(isEmpty() ) {
System.out.println( "Empty stack" );
return -1;
}
else {
return stackElements[top--];
}
}
}
Any kind of help is very much appreciated! :)