java - 将堆栈元素移回到单链表

标签 java linked-list stack

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

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

最佳答案

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

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

关于java - 将堆栈元素移回到单链表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22192807/

相关文章:

java - 我需要通过邮件从相机发送图像

Java FileNotFoundException 不工作

c++ - 删除链接列表中找到的所有特定键

java - 如何在Java中不阻塞地检查文件是否存在?

java - 如何将 Crashlytics 与 RoboVM iOS 绑定(bind)一起使用?

c - 向链表中插入一个元素

c - 链表的反转,不改变节点的链接

c++ - 递归搜索堆栈,但保持堆栈不变

java - 为什么 pop() 应该接受一个参数?

stack - 如何将一个圆圈中心化为一张卡片?