Categories
Uncategorized

143. Reorder List Leetcode Javascript Solution

The Problem:

You are given the head of a singly linked-list. The list can be represented as:

L0 → L1 → … → Ln - 1 → Ln

Reorder the list to be on the following form:

L0 → Ln → L1 → Ln - 1 → L2 → Ln - 2 → …

You may not modify the values in the list’s nodes. Only nodes themselves may be changed.

Example 1:

Input: head = [1,2,3,4]
Output: [1,4,2,3]

Example 2:

Input: head = [1,2,3,4,5]
Output: [1,5,2,4,3]

Constraints:

  • The number of nodes in the list is in the range [1, 5 * 104].
  • 1 <= Node.val <= 1000

The Solution:

var reorderList = function(head) {
    if(head == null) return head
let fast = head, slow = head
while(fast.next && fast.next.next){
    slow = slow.next
    fast = fast.next.next
}
    //console.log(fast.val)
    p2 = slow.next
    //console.log(p2)
    slow.next = null
    let prev = null
    while(p2){
        let next = p2.next
         p2.next = prev
        prev = p2
        p2 = next
    }
    console.log(prev)
    console.log(head)
    let part1 = head, part2 = prev
    while(part2){
        let p1 = part1.next
        let p2 = part2.next
        part1.next = part2
        part2.next = p1
        part1 = p1
        part2 = p2
    }
    return head
};

Leave a Reply

Your email address will not be published. Required fields are marked *