我正在尝试将列表元素移至堆栈并再次移回列表,颠倒它们的顺序。
我在将堆栈传输回列表的最后一点时遇到问题。 我一直在以不同的方式使用 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/