剑指Offer 06 从尾到头打印链表,Java解法参考
题目描述
难度: 简单
输入一个链表的头节点,从尾到头反过来返回每个节点的值(用数组返回)。
示例 1:
输入: head = [1,3,2]
输出: [2,3,1]
限制: 0 <= 链表长度 <= 10000
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/cong-wei-dao-tou-da-yin-lian-biao-lcof/
思路 1 (直接数组法)
思路
由于题目中给了链表长度的限制,所以可以建立一个大小为 10000 的数组,遍历链表,将值从后向前添加进数组。最后使用 Arrays.copyOfRange 取数组含有效数值的部分返回。
代码
class Solution {
public int[] reversePrint(ListNode head) {
int[] res = new int[10000];
ListNode tmp = head;
int n = 10000 - 1;
while (tmp != null) {
res[n] = tmp.val;
n--;
tmp = tmp.next;
}
return Arrays.copyOfRange(res, n + 1, 10000);
}
}
执行结果
思路 2 (栈过渡法)
思路
栈即LIFO表(后进先出表),可以通过栈达到从尾到头反转的效果。
代码
class Solution {
public int[] reversePrint(ListNode head) {
Stack<Integer> s = new Stack<>();
ListNode tmp = head;
while (tmp != null) {
s.push(tmp.val);
tmp = tmp.next;
}
int num = s.size();
int[] res = new int[num];
for (int i = 0; i < num; i++) {
res[i] = s.pop();
}
return res;
}
}
执行结果
写在最后
本系列博客仅记录转码过程中刷题时的解法。若有错误,欢迎交流与批评指正。官方解法请见力扣(LeetCode)官网。