【发布时间】: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