2014-03-05 40 views
1

我試圖將列表元素移動到堆棧並再次返回列表,並顛倒它們的順序。將堆棧元素移回到單個鏈接列表

我在將堆棧傳回列表中的最後一步遇到問題。 我一直在以不同的方式使用stack.pop();,但似乎沒有任何工作。

到目前爲止,我只能打印出stack.pop的輸出,但我確實希望能夠將堆棧內容傳回到列表中。

public class ReverseArray { 

    public static void main(String[] args) throws EmptyStackException { 
     // TODO Auto-generated method stub 

     MyLinkedList<GameEntry>myList = new MyLinkedList<>(); 

     //populate the list 
     myList.addFirst(new Node<GameEntry>(new GameEntry("Marche", 313), null)); 
     myList.addFirst(new Node<GameEntry>(new GameEntry("Apricot", 754), null)); 
     myList.addFirst(new Node<GameEntry>(new GameEntry("Dragon", 284), null)); 
     myList.addFirst(new Node<GameEntry>(new GameEntry("Erasure", 653), null)); 

     //print the list 
     System.out.println(myList); 
     System.out.println(); 
     System.out.println("New Reversed List:"); 
     //reverse the list elements 
     reverse(myList); 



    } 

    public static <V> void reverse (MyLinkedList<V> list) throws EmptyStackException{ 
     //code to reverse goes here 
     NodeStack<GameEntry> stack = new NodeStack<GameEntry>(); 
     Node<GameEntry> scores = list.getHead(); 

     for (int i = 0; i < list.getSize(); i++){ 
      stack.push(scores.getElement()); 
      scores = scores.getNext(); 

     } 

     while(!stack.isEmpty()){ 
      System.out.print(stack.pop() + " "); 

     } 

    }// end reverse 
}//end main 

回答

0

你應該保持順序從堆棧,所以在新LinkedList末添加它們:

while(!stack.isEmpty()){ 
    GameEntry entry = stack.pop(); 
    list.addLast(entry); 
} 
0

假設您希望列表僅包含反轉的元素,您必須首先清除列表。根據您的實施,您有一個clear()方法或必須多次呼叫remove(),直到列表爲empy。

之後,您可以像這樣添加代碼:

while(!stack.isEmpty()){ 
    GameEntry entry = stack.pop(); 
    list.addFirst(entry); 
} 

這樣,你應該在列表中元素的順序相反。

另一種方法是使用您的MyLinkedList實現List接口並使用Collections.reverse()


完全錯過訂單將與輸入列表上的相同。因此,您有兩種選擇:

  1. 使用隊列而不是堆棧。
  2. 使用第二個堆棧,獲取第一個堆棧的內容。這可能看起來像:

    NodeStack<GameEntry> secondStack = new NodeStack<GameEntry>(); 
    while(!stack.isEmpty()){ 
        secondStack.push(stack.pop()); 
    } 
    
    while(!secondStack.isEmpty()){ 
        GameEntry entry = secondStack.pop(); 
        list.addFirst(entry); 
    } 
    
+0

元素應該從列表後面添加保持相反的順序。 – user987339

+0

對,錯過了,修好了,謝謝! – Tarlen