DEV Community


Posted on

LeetCode 328. Odd Even Linked List (javascript solution)


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.


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

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

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

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

        cur =
        next =

    return head
Enter fullscreen mode Exit fullscreen mode

Top comments (1)

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)