输入一个链表的头节点,从尾到头反过来返回每个节点的值(用数组返回)。
示例 1:
输入:head = [1,3,2]
输出:[2,3,1]
来源与leetcode。
其实这道题就是反转链表改进版,要将反转之后的链表用数组返回值。我觉得主要考察的是如何讲链表转换成数组。
这里用的一个方式就是,在迭代的时候,统计结点的个数,之后在根据结点的个数来开辟同等大小的数组空间。
然后就是注意,反转列表之后的头结点是pre。
class Solution {
public int[] reversePrint(ListNode head) {
int length=0;
ListNode pre=null;
ListNode curr=head;
while(curr!=null){
ListNode next=curr.next;
curr.next=pre;
pre=curr;
curr=next;
length++;//统计结点个数,方便后面开辟相应大小的数组
}
int []res=new int[length];
int i=0;
//反转了链表之后,pre是链表头,所以从pre开始遍历
while(pre!=null){
res[i++]=pre.val;
pre=pre.next;
}
return res;
}
}