题目
解题思路
递归函数的难点在于如何理清楚程序执行。
定义一个递归函数前,必须要分清楚每一个小过程所做的动作,在此基础上分析最底部也就是理解basecase需要做的动作。
代码
/**
* Definition for singly-linked list.
* class ListNode {
* val: number
* next: ListNode | null
* constructor(val?: number, next?: ListNode | null) {
* this.val = (val===undefined ? 0 : val)
* this.next = (next===undefined ? null : next)
* }
* }
*/
// 利用递归的后序遍历操作
function reverseList(head: ListNode | null): ListNode | null {
if (head === null || head.next === null) return head;
// 假定递归函数能够成功的反转链表
const last = reverseList(head.next);
head.next.next = head;
head.next = null; //
return last // 最后一个节点一直返回,其余的节点改变next方向
};