在我当前的任务中,我应该在三个堆栈之间移动元素。我还有另一种写方法:getNumberOfMoves(),它应该计算堆栈之间的移动次数。
我想添加某种计算器,但是作业说我应该为此编写一个更具体的方法。关于如何使用一种方法计算移动次数的任何建议?
此外,我在move()方法方面遇到麻烦。我应该使用另一个类中的push()和pop()。我也做了一些事情,看看会发生什么,请参见下面的代码,但是我认为我应该使用递归来做到这一点。因此,基本情况应该是:如果第一个堆栈“ from”仅包含一个元素,则应将其直接移至“ to”,否则最后一个元素应移至“ help”堆栈,然后移至“ to” 。 但是,问题是,如果我以递归方式进行操作,是否不应该在方法中调用方法?那我应该如何使用pop()和push()?
多谢指教!
public class StackPlay {
/**
* Returns the current number of times an element has been moved
* @return the number of moves
*/
public static long getNumberOfMoves() {
}
public static void move(myStack from,
myStack to,
myStack help,
int n) {
help.push(from.pop());
to.push(help.pop());
}
public static void main(String[] args) {
int size = 3;
myStack from = new myStack(size);
myStack to = new myStack();
myStack help = new myStack();
System.out.println("Start state");
System.out.println(" From: " + from);
System.out.println(" To: " + to);
System.out.println(" Help: " + help);
System.out.println(" Number of moves: " + getNumberOfMoves());
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);
System.out.println(" Number of moves: " + getNumberOfMoves());
}
}
和单独的班级:
public class myStack {
private ArrayList<Integer> specStack;
public myStack() {
specStack = new ArrayList<Integer>();
}
public myStack(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 topEl = specStack.get(length);
specStack.remove(length);
return topEl;
}
}
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;
}
}