问题
输入一个链表的头节点,从尾到头反过来返回每个节点的值(用数组返回)
例子
思路
先反转链表,并记录结点个数,创建数组,遍历反转链表,依次将值插入数组
代码
class Solution {
public int[] reversePrint(ListNode head) {
ListNode hhead = new ListNode(-1);
int n=0;
while(head!=null)
{
n+=1;
ListNode temp = head.next;
head.next=hhead.next;
hhead.next = head;
head=temp;
}
int[] arr = new int[n];
hhead=hhead.next;
int i=0;
while(hhead!=null){
arr[i++]=hhead.val;
hhead=hhead.next;
}
return arr;
}
}