基本信息
TAG: 链表 递归 栈
URL: https://leetcode-cn.com/problems/cong-wei-dao-tou-da-yin-lian-biao-lcof/
LEVEL: 简单
POINT: 根据递归深度初始化
题目
输入一个链表的头节点,从尾到头反过来返回每个节点的值(用数组返回)。
题解
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
/* 法一:栈 */
// 时间复杂度 O(N): 入栈和出栈共使用 O(N) 时间。
// 空间复杂度 O(N): 辅助栈 stack 和数组 res 共使用 O(N) 的额外空间。
class Solution {
public int[] reversePrint(ListNode head) {
Stack<Integer> s = new Stack<>();
while (head != null) {
s.push(head.val);
head = head.next;
}
int[] res = new int[s.size()];
for (int i = 0; s.isEmpty() == false; i ++)
res[i] = s.pop();
return res;
}
}
/* 法二:递归 */
// 时间复杂度 O(N): 遍历链表,递归 N 次。
// 空间复杂度 O(N): 系统递归需要使用 O(N) 的栈空间。
class Solution {
List<Integer> list = new ArrayList<>();
public int[] reversePrint(ListNode head) {
reverse(head);
int[] res = new int[list.size()];
for (int i = 0; i < list.size(); i ++)
res[i] = list.get(i);
return res;
}
void reverse(ListNode node) {
if (node == null) return;
reverse(node.next);
list.add(node.val);
}
}
// 改进
class Solution {
int[] res;
int size = 0, cur = 0;
public int[] reversePrint(ListNode head) {
reverse(head);
return res;
}
void reverse(ListNode node) {
if (node == null) {
res = new int[size]; // 根据递归深度初始化
return;
}
size ++; // 递归深度
reverse(node.next);
res[cur] = node.val;
cur ++; // 数组下标
}
}