劍指offer 面試題5—從尾到頭打印鏈表

題目:
輸入一個鏈表的頭結點,從尾到頭反過來打印出每個結點的值。

考慮用棧

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);
    }

有個問題:

當鏈表非常長的時候,就會導致函數調用的層級很深,從而有可能導致函數調用棧溢出。顯示用棧基於循環實現的代碼魯棒性要好些。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章