我試圖將列表元素移動到堆棧並再次返回列表,並顛倒它們的順序。將堆棧元素移回到單個鏈接列表
我在將堆棧傳回列表中的最後一步遇到問題。 我一直在以不同的方式使用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
元素應該從列表後面添加保持相反的順序。 – user987339
對,錯過了,修好了,謝謝! – Tarlen