输入一个链表的头节点,从尾到头反过来返回每个节点的值(用数组返回)。 示例 1: 输入:head = [1,3,2] 输出:[2,3,1] 限制: 0 <= 链表长度 <= 10000栈
由于需要返回逆序,我们很容易就想到栈这种数据结构,将链表遍历,压入栈,再将其弹出存入res数组,得到的就是逆序的。时间复杂度:O(N),空间复杂度O(N).
class Solution {
public int[] reversePrint(ListNode head) {
if(head == null) return new int[0];
int cnt = 0;
Stack stack = new Stack();
while(head != null){
stack.push(head.val);
head = head.next;
cnt++;
}
int[] res = new int[cnt];
for(int i = 0;i < cnt;i++){
res[i] = stack.pop();
}
return res;
}
}



