题目
输入一个链表的头节点,从尾到头反过来返回每个节点的值(用数组返回)。
示例 1:
输入:head = [1,3,2]
输出:[2,3,1]
分析
扫描两趟,第一趟出链表长度
第二趟对数组赋值
这里第二趟用了递归
代码
/**
* 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 node = head;
int count = 0;
while (node != null) {
node = node.next;
count++;
}
int[] res = new int[count];
fun(head, res, count-1);
return res;
}
private void fun(ListNode node, int[] arr, int count) {
if (node != null) {
arr[count] = node.val;
fun(node.next, arr, --count);
}
}
}