【问题标题】:Java - How do write a method to reverse one stack onto another without destroying the original stack?Java - 如何编写一种方法来将一个堆栈反转到另一个堆栈而不破坏原始堆栈?
【发布时间】:2011-10-05 20:09:38
【问题描述】:

所以,我需要编写一个方法来使用 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。

【问题讨论】:

  • 这是一道作业题吗?如果是这样,您需要将其标记为这样。

标签: java stack reverse


【解决方案1】:

如果允许,您可以使用中间堆栈来执行此操作 --

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);
   }
}

【讨论】:

  • 啊。我没有“StackObj”,但我想我只是缺少“this”关键字来调用 stack1。我刚刚添加: StackClass newStack = new StackClass(); newStack.copyStack(this);并将其更改为从 newStack 复制和弹出,并且它起作用了。非常感谢!
猜你喜欢
  • 2013-12-26
  • 2017-08-12
  • 1970-01-01
  • 2019-08-08
  • 2022-10-17
  • 1970-01-01
  • 1970-01-01
  • 2019-04-26
  • 2022-11-27
相关资源
最近更新 更多