143. 重排链表

124 阅读1分钟

给定一个单链表 L 的头节点 head ,单链表 L 表示为:

L0 → L1 → … → Ln - 1 → Ln 请将其重新排列后变为:

L0 → Ln → L1 → Ln - 1 → L2 → Ln - 2 → … 不能只是单纯的改变节点内部的值,而是需要实际的进行节点交换。

var reorderList = function(head) {
 
     let slow = head
    let fast = head
    let pre = null
    let n = null
    let t = null
    let ans = new ListNode(-1)
    let cur = ans
    while(fast && fast.next){
        fast = fast.next.next
        const next = slow.next
        slow.next = pre
        pre = slow
        slow = next
    }
    while(slow){
        const next = slow.next
        slow.next = n
        n = slow
        slow = next
    }
     while(pre){
        const next = pre.next
        pre.next = t
        t = pre
        pre = next
    }
    while(t&&n){
       ans.next = t
       t=t.next
       ans = ans.next
       ans.next = n
       n = n.next
       ans = ans.next
    }
    return cur.next
};