DEV Community

codingpineapple
codingpineapple

Posted on

LeetCode 328. Odd Even Linked List (javascript solution)

Description:

Given the head of a singly linked list, group all the nodes with odd indices together followed by the nodes with even indices, and return the reordered list.

The first node is considered odd, and the second node is even, and so on.

Note that the relative order inside both the even and odd groups should remain as it was in the input.

Solution:

Time Complexity : O(n)
Space Complexity: O(1)

var oddEvenList = function(head) {
    // Handle base cases
    if(!head || !head.next || !head.next.next) {
        return head
    }

    // Set two pointers
    let cur = head
    let next = head.next

    // Set the odd.next to point to the next even node
    // Move each pointer up one node on each iteration
    while(next && next.next) {
        const temp = next.next
        const temp2 = cur.next

        cur.next = temp
        next.next = temp.next
        temp.next = temp2

        cur = cur.next
        next = next.next
    }

    return head
};
Enter fullscreen mode Exit fullscreen mode

Top comments (1)

Collapse
 
aarone4 profile image
Aaron Reese

Can't write code on the phone...
ArrOdd = arrOriginal.filter(i, idx) => idx % 2 == 0
ArrEven = arrOriginal.filter(i, idx) => idx % 2 == 1
Return (arrOdd...arrEven)