题目描述:
输入一个链表的头节点,从尾到头反过来返回每个节点的值(用数组返回)。
示例 1:
输入:head = [1,3,2]
输出:[2,3,1]
限制:
0 <= 链表长度 <= 10000
代码:
class Solution {
//集合,时间复杂度O(n)
public int[] reversePrint(ListNode head) {
List<Integer> list = new ArrayList<>();
while(head != null){
list.add(head.val);
head = head.next;
}
//利用工具类中的翻转函数进行翻转
Collections.reverse(list);
//不能直接得到int[]数组,所以采取循环赋值的方法
int[] arr = new int[list.size()];
for(int i = 0; i < list.size(); i++){
arr[i] = list.get(i);
}
return arr;
}
}
还可以用栈来做。
class Solution {
public int[] reversePrint(ListNode head) {
Stack<Integer> stack = new Stack<>();
while(head != null){
stack.push(head.val);
head = head.next;
}
int[] arr = new int[stack.size()];
for(int i = 0; i < arr.length; i++){
arr[i] = stack.pop();
}
return arr;
}
}