0

此方法应该返回当前堆栈的副本,​​其中项目反转。

public LinkedStack<E> reversed()
{
    LinkedStack<E> that= new LinkedStack<E>();
    if(this.isEmpty()==true){
        return this;
    }
    else{
        while(this.isEmpty())//changed from this.isEmpty()==true
            {
            Node<E> snode=this.top;
            that.push(snode.getData());
            this.pop();
            snode=snode.getLink();
                    /*
                      that.push(pop()); works perfectly
                    */

            }
        return that;
        }
    }

更新 好的答案之一似乎让我更接近解决方案。它有效,但仅适用于方法中创建的堆栈。我遇到的问题是将它链接到这个堆栈,以便我可以返回堆栈的副本this。我正在使用链接堆栈。

4

2 回答 2

3

为什么不

while(!isEmpty()) {
   revertStack.push(pop());
}

同时查看您的原始循环,特别是第一行,看看可能导致您的问题的原因

于 2013-10-07T00:21:09.223 回答
0

创建了三个 LinkedStacks。复制第一到第二,然后第二到第三,然后第三到第一

public LinkedStack<E> reversed()
{
    LinkedStack<E> that= new LinkedStack<E>();
    LinkedStack<E> that1= new LinkedStack<E>();
    LinkedStack<E> that2= new LinkedStack<E>();

    if(this.isEmpty()==true){
        return this;
    }
    else{
        while(this.isEmpty())//changed from this.isEmpty()==true
            {
        while(!this.isEmpty()){that.push(this.pop());}
        while(!that.isEmpty()){that1.push(this.pop());}
        while(!that1.isEmpty()){this.push(this.pop());}

            }
        return that;
        }
    }
于 2013-10-07T20:10:24.027 回答