一、题目
输入一个链表的头节点,从尾到头反过来返回每个节点的值(用数组返回)。
示例 1:
输入:head = [1,3,2]
输出:[2,3,1]
限制:
- 0 <= 链表长度 <= 10000
二、解决
1、递归
思路: 先递归到最后一个节点,将其添加如数组中,再往前逐个返回,逐个添加。
代码:
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
ArrayList<Integer> tmp = new ArrayList<Integer>();
public int[] reversePrint(ListNode head) {
recur(head);
int[] res = new int[tmp.size()];
for(int i = 0; i < res.length; i++)
res[i] = tmp.get(i);
return res;
}
void recur(ListNode head) {
if(head == null) return;
recur(head.next);
tmp.add(head.val);
}
}
时间复杂度:
O
(
n
)
O(n)
O(n)
空间复杂度:
O
(
n
)
O(n)
O(n)
2、辅助栈
思路:
遍历至最后一个节点,再逐个添加进数组中。
注意:Java 不太推荐用 Vector 和 Stack,最好使用 LinkedList 实现链表、队列等数据结构,因为其中Stack底层是数组,扩容时效率低,而且还有synchronized方法,耗时较高。
代码:
class Solution {
public int[] reversePrint(ListNode head) {
LinkedList<Integer> stack = new LinkedList<Integer>();
while(head != null) {
stack.addLast(head.val);
head = head.next;
}
int[] res = new int[stack.size()];
for(int i = 0; i < res.length; i++)
res[i] = stack.removeLast();
return res;
}
}
时间复杂度:
O
(
n
)
O(n)
O(n)
空间复杂度:
O
(
n
)
O(n)
O(n)
三、参考
1、面试题06. 从尾到头打印链表(递归法、辅助栈法,清晰图解)
2、为什么 java.util.Stack不被官方所推荐使用!