2014-03-05 37 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