题目:
输入一个链表的头结点,从尾到头反过来打印出每个结点的值。
考虑用栈
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);
}
有个问题:
当链表非常长的时候,就会导致函数调用的层级很深,从而有可能导致函数调用栈溢出。显示用栈基于循环实现的代码鲁棒性要好些。
本文介绍两种方法实现链表的逆序打印:一是利用栈的特性通过循环遍历链表并压栈,再依次弹出;二是采用递归方式,先递至链表尾部再返回并打印各节点值。讨论了递归方法可能遇到的栈溢出问题。
188

被折叠的 条评论
为什么被折叠?



