Offer.P6[从尾到头打印链表]

方法一:递归

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {

List<Integer> list;

public int[] reversePrint(ListNode head) {
list = new ArrayList<>();
reverse(head);
int n = list.size();
int[] ans = new int[n];
for (int i = 0; i < n; ++i) {
ans[i] = list.get(i);
}
return ans;
}

private void reverse(ListNode head) {
if (head == null) return;
reverse(head.next);
list.add(head.val);
}
}
  • 时间复杂度:$O(n)$
  • 空间复杂度:$O(n)$

方法二:栈

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {

public int[] reversePrint(ListNode head) {
Deque<Integer> stack = new ArrayDeque<>();
while (head != null) {
stack.push(head.val);
head = head.next;
}
int n = stack.size();
int[] ans = new int[n];
for (int i = 0; i < n; ++i) {
ans[i] = stack.pop();
}
return ans;
}
}
  • 时间复杂度:$O(n)$
  • 空间复杂度:$O(n)$