剑指offer 面试题5—从尾到头打印链表

    xiaoxiao2026-02-20  13

    题目: 输入一个链表的头结点,从尾到头反过来打印出每个结点的值。

    考虑用栈

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

    有个问题:

    当链表非常长的时候,就会导致函数调用的层级很深,从而有可能导致函数调用栈溢出。显示用栈基于循环实现的代码鲁棒性要好些。

    最新回复(0)