我们先来看一道题
206. 反转链表
这次我们先看代码:
/**
* Definition for singly-linked list.
* function ListNode(val, next) {
* this.val = (val===undefined ? 0 : val)
* this.next = (next===undefined ? null : next)
* }
*/
/**
* @param {ListNode} head
* @return {ListNode}
*/
var reverseList = function(head) {
//结束条件
if(head === null || head.next === null) {
return head;
}
let last = reverseList(head.next);
head.next.next = head;
head.next = null;
return last;
};
一、分析
-
首先,我们要先搞清楚这个递归函数的作用。这个递归函数我们用来返回head结点之后的链表的反转链表的头结点(
输⼊⼀个节点 head,将「以 head 为起点」的链表反转,并返回