【问题描述】[简单]
输入一个链表的头节点,从尾到头反过来返回每个节点的值(用数组返回)。
示例 1:
输入:head = [1,3,2]
输出:[2,3,1]
限制:
0 < 链表长度 <= 10000
【解答思路】
1. 常规思路
- 遍历链表 得到链表个数
- 新建数组 遍历链表复制val
时间复杂度:O(N) 空间复杂度:O(N)
public int[] reversePrint(ListNode head) {
int count = 0;
ListNode temp = head;
while (temp != null) {
count++;
temp = temp.next;
}
int[] res = new int[count];
for (int i = count - 1; i > -1; i--) {
res[i] = head.val;
head = head.next;
}
return res;
}
2. 栈
时间复杂度:O(N) 空间复杂度:O(1)
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;
}
}
3. 递归
时间复杂度:O(N) 空间复杂度:O(1)
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);
}
}
【总结】
1.数组是不能使用集合的反转方法的,可以自定义方法实现数组反转
public static int[] reserve( int[] arr ){
int[] arr1 = new int[arr.length];
for( int x=0;x<arr.length;x++ ){
arr1[x] = arr[arr.length-x-1];
}
return arr1 ;
}
2.ArrayList使用函数反转
3.不建议使用stack
为什么用LinkedList不用Stack
基于 Vector 实现的栈 Stack底层是数组 扩容开销大
Java并不推荐使用java.util.stack来进行栈的操作,而是推荐使用一个双端队列deque
详情链接:https://www.cnblogs.com/cosmos-wong/p/11845934.html
转载链接:https://leetcode-cn.com/problems/cong-wei-dao-tou-da-yin-lian-biao-lcof/solution/mian-shi-ti-06-cong-wei-dao-tou-da-yin-lian-biao-d/