/** * 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 {void}Do not return anything, modify head in-place instead. */ const reorderList = function (head) { if (head === null || head.next === null) { return head } let pre = null let slow = head let fast = head while (fast !== null && fast.next !== null) { pre = slow slow = slow.next fast = fast.next.next } pre.next = null slow = reverseList (slow) return merge(head, slow) }
functionreverseList (head) { let pre = null let cur = head while (cur !== null) { let temp = cur.next cur.next = pre pre = cur cur = temp } return pre }
functionmerge (head1, head2) { let p1 = head1 let p2 = head2 while (p1 !== null) { let temp1 = p1.next let temp2 = p2.next p1.next = p2 // 如果p1是最后一个节点,应在p1后插入p2时终止循环 if (temp1 === null) { break } p2.next = temp1 p1 = temp1 p2 = temp2 } return head1 }