0%

剑指 Offer 06. 从尾到头打印链表

剑指 Offer 06. 从尾到头打印链表

题目来源:剑指 Offer 06.

题目链接:https://leetcode-cn.com/problems/cong-wei-dao-tou-da-yin-lian-biao-lcof/

题目描述

输入一个链表的头节点,从尾到头反过来返回每个节点的值(用数组返回)。

示例 1:

1
2
输入:head = [1,3,2]
输出:[2,3,1]

限制:

0 <= 链表长度 <= 10000

问题分析

示例代码

1
2
3
4
5
6
7
8
9
10
11
12
13
public int[] reversePrint(ListNode head) {
//使用栈完成反转
Stack<Integer> stack = new Stack<>();
ListNode pNode = head;
while(pNode !=null){
stack.push(pNode.val);
pNode = pNode.next;
}
int[]ans = new int[stack.size()];
for(int i =0;i<ans.length;i++)
ans[i]=stack.pop();
return ans;
}

执行结果:

image-20210207220941087

递归

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
List<Integer> list= new ArrayList<>();
public int[] reversePrint(ListNode head) {
//使用递归完成反转
ListNode pNode = head;
reverseRecursion(pNode);
int[]ans = new int[list.size()];
for(int i =0;i<ans.length;i++)
ans[i]=list.get(i);
return ans;
}
private void reverseRecursion(ListNode pNode){
if(pNode == null)
return ;
reverseRecursion(pNode.next);
list.add(pNode.val);
return ;
}

执行结果:

image-20210207224552623

-------------本文结束感谢您的阅读-------------
坚持原创技术分享,您的支持将鼓励我继续创作!

欢迎关注我的其它发布渠道