题目
输入一个链表的头节点,从尾到头反过来返回每个节点的值(用数组返回)。
示例 1:
输入:head = [1,3,2]
输出:[2,3,1]
限制:
0 <= 链表长度 <= 10000
思路
因为递归可以实现逆向遍历的效果,所以可以使用递归来逐个返回节点。
实现
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
// 记录返回的结果
int[] result;
// 记录链表的长度
int count = 0;
public int[] reversePrint(ListNode head) {
// 递归遍历整个链表
recur(head, 0);
return result;
}
/**
* 遍历链表
* @param head 遍历的链表
* @param index 链表的索引(0表示表头)
*/
public void recur(ListNode head, int index) {
// 递归结果条件:节点为空节点(即遍历完链表)
if (head == null) {
// 初始化返回的结果(遍历结束才知道链表的长度)
result = new int[count];
return;
}
// 计算链表长度
count ++;
// 递归遍历下一个链表
recur(head.next, index + 1);
// 将当前节点的值添加的结果中(count为链表长度、index为当前节点的索引,所以要-1)
result[count - index - 1] = head.val;
}
}