0

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! :)

nakuta
  • 1
  • 3
    [Why is “Can someone help me?” not an actual question?](http://meta.stackoverflow.com/questions/284236/why-is-can-someone-help-me-not-an-actual-question) – azurefrog Jan 09 '16 at 15:27
  • 1
    I'm not looking for someone who is going to solve the entire task, as stated in topic description I'm looking for some hints, where to start for example. – nakuta Jan 09 '16 at 15:29
  • 1
    @azurefrog it's a much a question as your question. – nicomp Jan 09 '16 at 15:37
  • 1
    @nicomp My question is self-answered, and I wrote it so that I could use it as a target for flagging duplicates. If you have any suggestions to make it more clear please let me know and I will improve it. – azurefrog Jan 09 '16 at 15:56
  • 1
    @nakuta Please take another look at the meta article I linked. The point is that "can you give me some hints re: tower of hanoi?" is not very likely to be useful to other people. A better question would be "how do I convert a recursive program to an iterative one?", using your program as a concrete example. – azurefrog Jan 09 '16 at 16:00
  • 2
    In any case, take a look at [Ways to go from recursion to iteration](http://stackoverflow.com/questions/159590/way-to-go-from-recursion-to-iteration) for some general ideas on converting your program. – azurefrog Jan 09 '16 at 16:00

0 Answers0