题目要求
输入一个链表的头节点,从尾到头反过来返回每个节点的值(用数组返回)。
示例 1:
输入:head = [1,3,2]
输出:[2,3,1]
class Solution {
public int[] reversePrint(ListNode head) {
ListNode cur = head;
int count = 0;
while(cur != null){
count ++;
cur = cur.next;
}
int [] arr = new int[count];
count --;
cur = head;
while(cur != null && count >= 0){
arr[count]
}
}
}
//第二种写法
/**
* 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<>();
ListNode p = head;
while(p != null){
stack.push(p.val);
p = p.next;
}
p = head;
int[] number = new int[stack.size()];
for(int i=0; i<number.length; i++){
number[i] = stack.pop();
}
return number;
}
}
/*
执行用时:2 ms, 在所有 Java 提交中击败了37.35%的用户
内存消耗:39.1 MB, 在所有 Java 提交中击败了54.81%的用户
*/