2013-10-07 34 views
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堆棧的副本。我正在使用鏈接堆棧。

+3

您不需要使用'this.',除非有一個具有相同名稱的局部變量。而'== true'是不必要的。 – Dukeling

+1

在一種情況下返回原來的而不是新的對象(空的)而不是另一種是不可取的。如果有人修改了他們得到的副本,該怎麼辦? – clwhisk

回答

3

爲什麼不

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

同時看看你的原始循環特別是第一線,看看有什麼可能導致您的問題

+0

我接近解決問題,我只需要一種方法來設置這個堆棧到那個堆棧 – gwrw

+0

哪個測試生成NPE?您是否將您的代碼與我的代碼進行了比較,發現您的代碼在做什麼不同? –

+0

是的。謝謝,但我有一個小問題。該方法應該返回一個「this」棧的副本。我將如何去返回這個反轉的副本。我試着設置這個,並返回這個,但顯然沒有帶我到任何地方。有任何想法嗎? – gwrw

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; 
     } 
    } 
+0

你到底在做什麼? –