Offer 驾到,掘友接招!我正在参与2022春招打卡活动,点击查看活动详情。
一、题目描述:
题目来源:LeetCode>从尾到头打印链表
输入一个链表的头节点,从尾到头反过来返回每个节点的值(用数组返回)。
示例 1:
输入:head = [1,3,2] 输出:[2,3,1]
限制:
0 <= 链表长度 <= 10000
二、思路分析:
- 题目中描述了一个很大的特点,就是先进后出,对于这类数据结构,我们很容易联想到:栈
- 栈的特点是后进先出,即最后压入栈的元素最先弹出
- 创建一个栈,用于存储链表的节点
- 创建一个指针,初始时指向链表的头节点
- 将指针指向的节点压入栈内
- 将指针移到当前节点的下一个节点
三、AC 代码:
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public int[] reversePrint(ListNode head) {
Stack<ListNode> stack = new Stack<ListNode>();
ListNode temp = head;
while (temp != null) {
stack.push(temp);
temp = temp.next;
}
int size = stack.size();
int[] result = new int[size];
for (int i = 0; i < size; i++) {
result[i] = stack.pop().val;
}
return result;
}
}
复制代码
时间复杂度:O(n)。
四、总结:
从链表的头节点开始,依次将每个节点压入栈内,然后依次弹出栈内的元素并存储到数组中,最后弹出栈内的元素。
此外,还可以使用一种递归法。
先走至链表末端,回溯时依次将节点值加入列表 ,这样就可以实现链表值的倒序输出。
递推阶段: 每次传入 head.next ,以 head == null(即走过链表尾部节点)为递归终止条件,此时直接返回。 回溯阶段: 层层回溯时,将当前节点值加入列表,即tmp.add(head.val)。 最终,将列表 tmp 转化为数组 result ,并返回即可。
class Solution {
ArrayList<Integer> tmp = new ArrayList<Integer>();
public int[] reversePrint(ListNode head) {
recursion(head);
int[] result = new int[tmp.size()];
for(int i = 0; i < result.length; i++)
result[i] = tmp.get(i);
return result;
}
void recursion(ListNode head) {
if(head == null) return;
recursion(head.next);
tmp.add(head.val);
}
}
复制代码
时间复杂度 O(N)。