【问题标题】:Moving stack elements back to a Single linked list将堆栈元素移回单链表
【发布时间】:2014-03-05 08:54:52
【问题描述】:

我正在尝试将列表元素移入堆栈并再次移回列表,颠倒它们的顺序。

我在将堆栈传输回列表的最后一位时遇到问题。 我一直在以不同的方式使用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

【问题讨论】:

    标签: java linked-list stack


    【解决方案1】:

    您应该保持堆栈中的顺序,因此将它们添加到新 LinkedList 的末尾:

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

    【讨论】:

      【解决方案2】:

      假设您希望列表仅包含反转的元素,您必须首先清除列表。根据您的实现,您有一个 clear() 方法或必须多次调用 remove() 直到列表为空。

      之后你可以像这样添加代码:

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

      这样你的元素在列表中的顺序应该是相反的。

      另一种方法是使用您的 MyLinkedList 实现 List 接口并使用 Collections.reverse()


      完全错过了订单与输入列表中的相同。因此,您有两种选择:

      1. 使用队列而不是堆栈。
      2. 使用第二个 Stack 填充您的第一个 Stack 的内容。这可能看起来像:

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

      【讨论】:

      • 元素应该从列表的后面添加以保持相反的顺序。
      猜你喜欢
      • 2019-02-23
      • 2015-07-05
      • 2016-03-08
      • 1970-01-01
      • 1970-01-01
      • 2020-07-10
      • 1970-01-01
      • 2010-10-28
      • 1970-01-01
      相关资源
      最近更新 更多