因此,我需要编写一个方法,使用 stack1.reverseStack(stack2) 将 stack1 反转到 stack2。我需要在不破坏 stack1 的情况下执行此操作。这就是我到目前为止所拥有的......
public void reverseStack(StackClass otherStack)
{
int x = stackTop;
for (int i = 0; i < x; i++)
{
otherStack.push(copy.top());
copy.pop();
}
}
它只能工作,我无法找到一种不破坏 stack1 的方法。我想过制作一个复制堆栈并使用它,但我不知道如何在方法中复制 stack1。
最佳答案
如果允许的话,您可以使用中间堆栈来完成此操作 --
public void reverseStack(StackClass otherStack)
{
StackClass newStack = new StackClass();
StackObj obj = null;
while ( (obj = this.pop()) != null ) {
otherStack.push(obj);
newStack.push(obj);
}
// Now push back from newStack to this stack
while ( (obj = newStack.pop() ) != null ) {
this.push(obj);
}
}
关于Java - 如何编写一种方法将一个堆栈反转到另一个堆栈而不破坏原始堆栈?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6702151/