如何递归在堆栈之间移动元素?

时间:2019-04-04 16:05:49

标签: java recursion arraylist towers-of-hanoi

我有一个河内问题塔。我有三个堆栈,我想使用称为move()的方法以一定顺序递归移动元素。我应该在另一个从堆栈中添加和删除元素的类中使用方法pop()和push()。

我尝试实现此方法,但它仅适用于第一种基本情况,例如。如果n == 1。

 public static void move(SpecialStack from, 
                         SpecialStack to, 
                         SpecialStack help, 
                         int n) {
   if (n == 1) {
 to.push(from.pop());
 }
   else {
     move(from, to, help, n-1);
     to.push(from.pop());
     move(help, to, from, n-1);
   }
 }

 public static void main(String[] args) {
    int size = 3;
    SpecialStack from = new SpecialStack(size);
    SpecialStack to = new SpecialStack();
    SpecialStack help = new SpecialStack();
    System.out.println("Start state");
    System.out.println("   From: " + from);
    System.out.println("   To:   " + to);
    System.out.println("   Help: " + help);
    move(from, to, help, size);
    System.out.println("End state");
    System.out.println("   From: " + from);
    System.out.println("   To:   " + to);
    System.out.println("   Help: " + help);

我从push()方法得到的错误是我自己的错误,“数字太高!”来自另一个类SpecialStack:


 import java.util.*;
import java.util.ArrayList;

public class SpecialStack {

  private ArrayList<Integer> specStack;

  public SpecialStack() {
    specStack = new ArrayList<Integer>();
  }

  public SpecialStack(int n) {         
    this.specStack = new ArrayList<Integer>(n);
      int i;
      for (i=0; i<n; i++) {
        specStack.add(i, n-i);
      }
    }


  public void push(int x) { 
    if (specStack.size() == 0) { 
      specStack.add(x);
    }
    else if (x > specStack.get(specStack.size() -1)) {
      throw new RuntimeException("Number too high");
    }
    else {
      specStack.add(x); 
    }
  }

  public int pop() { 
    if (specStack.size() == 0) {
      throw new RuntimeException("Empty stack");
    }
    else {
      int length = specStack.size() -1;
      int topNumber = specStack.get(length); 
      specStack.remove(length);
      return topNumber;
    }
  }

  public String toString() {
    String arrList = "[";
    int i;
    for (i = 0; i < specStack.size(); i++) { 
      if (i == specStack.size() -1) {
        arrList = arrList + specStack.get(i);
      } 
      else {
        arrList = arrList + specStack.get(i) + ",";}
    }
  arrList = arrList + "]";
  return arrList;
  }
}

我不明白为什么会出现此错误。而且,move()方法正确吗?感谢您的建议!

1 个答案:

答案 0 :(得分:0)

您的代码中有一个愚蠢的错误。在您的其他部分,当n > 1时,您应该做

move(from, help, to, n-1);

代替

move(from, to, help, n-1);

请记住,对于大于1的任何事物,您都将“帮助”队列视为除一个钉子之外的所有钉子的目的地队列。完成此操作后,将最低钉子移到原始的“ to”队列,并考虑原始的“ help”为“ from”和原始的“ from”为“ help”来重复这些操作。希望能有所帮助。