/** * @param {ListNode} head * @return {ListNode} */ var reverseList = function(head) { if(!head){ return head } let pre=null let cur=head let temp while(cur){ temp=cur.next cur.next=pre pre=cur cur=temp } return pre };
递归法相对抽象一些,但是其实和双指针法是一样的逻辑,同样是当cur为空的时候循环结束,不断将cur指向pre的过程。关键是初始化的地方,可能有的同学会不理解, 可以看到双指针法中初始化 cur = head,pre = NULL,在递归法中可以从如下代码看出初始化的逻辑也是一样的,只不过写法变了。具体可以看代码(已经详细注释),双指针法写出来之后,理解如下递归写法就不难了,代码逻辑都是一样的。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
/** * @param {ListNode} head * @return {ListNode} */ var reverseList = function(head) { returnreverse(head,null) }; constreverse=(cur,pre)=>{ if(!cur){ return pre } let temp=cur.next cur.next=pre returnreverse(temp,cur) }
4. 两两交换链表中的节点
24
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
/** * @param {ListNode} head * @return {ListNode} */ var swapPairs = function(head) { let dummy = newListNode() dummy.next = head let current = dummy while (current.next !== null && current.next.next !== null) { let n1 = current.next let n2 = current.next.next n1.next = n2.next current.next = n2 n2.next = n1 current = n1 } return dummy.next };