Given a singly linked list L: L0 → L1 → .. → Ln-1 → Ln, reorder it to: L0 → Ln → L1 → Ln-1 → L2 → Ln-2 →
You may not modify the values in the list's nodes
, only nodes itself may be changed.
Example 1:
Given 1->2->3->4, reorder it to 1->4->2->3.
Example 2:
Given 1->2->3->4->5, reorder it to 1->5->2->4->3.
这道题可作如下转化:
快慢指针即 quick 指针每次走两步, slow 指针每次走一步, 同 148.Sort_List
s qdummy -> 1 -> 2 -> 3 -> 4 -> 5 -> NULL步骤一: 拆分 head 链表成 `left`、`right` 两个链表;l1 -> 2 -> 3 -> nullr4 -> 5 -> NULL步骤二: 翻转 right 链表l1 -> 2 -> 3 -> nullr5 -> 4 -> NULL步骤三: 衔接 left、right 两个链表;l1 -> 5 -> 2 -> 3 -> NULLr4 -> NULL
步骤二中翻转链表的图解大致如下:
cur next1 -> 2 -> 3 -> nullprev curnull <- 1 <- 2 -> 3 -> nullprev curnull <- 1 <- 2 <- 3 -> nullprevnull <- 1 <- 2 <- 3 -> null
/*** Definition for singly-linked list.* function ListNode(val) {* this.val = val;* this.next = null;* }*//*** @param {ListNode} head* @return {void} Do not return anything, modify head in-place instead.*/var reorderList = function(head) {const dummy = new ListNode(0)dummy.next = headlet slow = dummylet quick = dummywhile (quick && quick.next) {slow = slow.nextquick = quick.nextquick = quick.next}let right = slow.nextslow.next = nulllet left = dummy.nextright = reverseList(right)while (left && right) {let lNext = left.nextlet rNext = right.nextright.next = left.nextleft.next = rightleft = lNextright = rNext}return dummy.next}var reverseList = (list) => {let prev = nulllet cur = listwhile (cur) {let next = cur.nextcur.next = prevprev = curcur = next}return prev}
148(快慢指针)、234