题目:
输入一个链表的头节点,从尾到头反过来返回每个节点的值(用数组返回)。
解析:
思路很简单,可以直接先把链表翻转,同时记录链表长度,初始化数组;再遍历逆转的链表,添加到数组里。
代码:
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public int[] reversePrint(ListNode head) {
ListNode new_head=null;
int len=0;
while(head!=null){ //这里是链表反转
ListNode temp=head.next;
head.next=new_head;
new_head=head;
head=temp;
len++;
}
int[] arr=new int[len]; //定义数组
int n=0;
while(new_head!=null){ //遍历
arr[n]=new_head.val;
new_head=new_head.next;
n++;
}
return arr;
}
}