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

来源:互联网 发布:八音度调音软件 编辑:程序博客网 时间:2024/05/21 16:22

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

考虑用栈

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 0
原创粉丝点击