题目 输入一个链表的头节点,从尾到头反过来返回每个节点的值(用数组返回)。
示例 1:
输入:head = [1,3,2]
输出:[2,3,1]
来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/fan-zhuan-lian-biao-lcof
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
public int[] reversePrint(ListNode head) {
ListNode temp=head;
int len=0; //保存结果数组长度
while (temp !=null){//获取链表长度
temp=temp.next;
len++;
}
int[] res=new int[len];
//从后往前依次给数组赋值
while (head!=null){
res[--len]=head.val;
head=head.next;
}
return res;
}