输入一个链表的头节点,从尾到头反过来返回每个节点的值(用数组返回)。
示例 1:
输入:head = [1,3,2] 输出:[2,3,1]
/**
感觉用list也差不多,咋时间差那么多。栈直接取栈顶,list倒取。
*/
class Solution {
public int[] reversePrint(ListNode head) {
if(head==null)return new int[0];
Stack<Integer> s=new Stack();
while(head!=null){
s.push(head.val);
head=head.next;
}
int[] nums=new int[s.size()];
for(int i=0;i<nums.length;i++){
nums[i]=s.pop();
}
return nums;
}
}
/**
递归,如果后续节点不为空,进入递归
**/
class Solution {
public int[] reversePrint(ListNode head) {
List<Integer> list=new ArrayList<Integer>();
reverse(head,list);
int len=list.size();
int[] arr=new int[len];
for(int i=0;i<len;i++){
arr[i]=list.get(i);
}
return arr;
}
void reverse(ListNode head,List<Integer> list){
if(head==null)return;
if(head.next!=null){
reverse(head.next,list);
}
list.add(head.val);
}
}