![](/img/trans.png)
[英]How does recursion works in printing the linked list elements in reverse order?
[英]Printing out elements of a linked list in reverse
我正在練習我的數據結構並嘗試在 HackerRank上以相反的順序打印鏈表的元素。
我已經多次查看我的解決方案,但我不明白為什么它是錯誤的。
我的解決方案:
static void reversePrint(SinglyLinkedListNode head) {
if (head==null){
return;
}
ArrayList<Integer> intList = new ArrayList<>();
while(head!=null){
intList.add(head.data);
head = head.next;
}
Collections.sort(intList, Collections.reverseOrder());
for(int i: intList){
System.out.println(i);
}
}
感謝有人可以幫助指出我的錯誤。
使用Stack
而不是ArrayList
static void reversePrint(SinglyLinkedListNode head) {
if (head==null){
return;
}
Deque<Object> intList = new ArrayDeque<>();
while(head!=null){
intList.push(head.data);
head = head.next;
}
while(!intList.isEmpty()){
System.out.println(intList.pop());
}
}
感謝是否有人可以幫助指出我的錯誤
問題
您使用了ArrayList
,其行為是F irst I n F irst O ut ,因此當您for
-loop intList
時打印的元素順序與鏈表中的順序相同,從head
開始。
可能的解決方案
要解決您的方法,您可以簡單地:
1- 使用List#add(int index, E element) 將每個元素始終插入intList
的 position 零:
// ...
intList.add(0, head.data);
// ...
2-或者,您可以替換用於“還原”元素的數據結構。
例如,您可以使用任何 Last I n F irst O ut數據結構,例如Queue
或Deque
在它們的 LIFO 變體中。
另一種選擇
為您提供另一個完全不同的解決方案,您可以以遞歸方式實現它,如下所示:
static void reversePrint(SinglyLinkedListNode head) {
if (head != null) {
reversePrint(head.next);
System.out.println(head.data);
}
}
如果head
是null
,不要打印任何東西。 否則,首先reversePrint
next
元素,然后是當前元素( head.data
)......這將導致反轉效果。
值得注意的是,這並沒有顛倒元素的順序,也就是說,它不會修改每個元素的next
一個。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.