題目:
輸入一個鏈表的頭結點,從尾到頭反過來打印出每個結點的值。
考慮用棧
public void invertedList1(ListNode head) {
if (head == null) {
return;
}
ListNode p = head;
Stack<Integer> stack = new Stack<Integer>();
while (p != null) {
stack.push(p.val);
p = p.next;
}
while (!stack.isEmpty()) {
System.out.println(stack.pop());
}
}
用遞歸
public void invertedList(ListNode head) {
if (head == null) {
return;
}
invertedList(head.next);
System.out.println(head.val);
}
有個問題:
當鏈表非常長的時候,就會導致函數調用的層級很深,從而有可能導致函數調用棧溢出。顯示用棧基於循環實現的代碼魯棒性要好些。