1. 程式人生 > >5、從尾部打印鏈表

5、從尾部打印鏈表

arr tlist clas head 指針 缺點 int != 有一個

思路1:用額外存儲元素,然後遍歷輸出。如棧或arrayList,前插入,沒錯都插入到最前面的節點。
import java.util.ArrayList;
public class Solution {
public ArrayList<Integer> printListFromTailToHead(ListNode listNode) {
if(listNode == null){
return new ArrayList<>();
}
int num = 0;
ListNode head = listNode;
//計算鏈表長度
while(listNode != null) {
num++;
listNode = listNode.next;

}
ArrayList<Integer> lists = new ArrayList<>();

//倒序插入
while(head != null) {
lists.add(0, head.val);

head = head.next;
}
return lists;
}
}

思路2:遞歸實現。每當訪問一個節點,就遞歸輸出後面的節點,然後輸出自己。缺點:當鏈表長的時候,遞歸深度太深,會調用棧溢出。
測試:
只有一個節點,有多個節點。
空指針。

5、從尾部打印鏈表