DEV Community

Subramanya Chakravarthy
Subramanya Chakravarthy

Posted on

Odd Even Linked List - LeetCode

Given a singly linked list, group all odd nodes together followed by the even nodes. Please note here we are talking about the node number and not the value in the nodes.

Linked List is all about pointers/references. We need to have a visual of node and next to solve it

Single Linked List

If you observe above diagram, we need to create two linked list odd and even. Creating them is easy loop through the nodes and as you pass all you have to change the odd's next node to even's next node, because we want to skip even in oddHead and similarly even's next node to odd's next node

Here is the solution:

/**
 * @param {ListNode} head
 * @return {ListNode}
 */
var oddEvenList = function(head) {
    // Handle edge cases
    if(head == null) return null
    let odd = head
    let even = odd.next
    let evenHead = even

    while(even != null && even.next != null) {
        // assign odd's next node to next odd node
        odd.next = even.next
        // move odd pointer to the next one
        odd = odd.next
        // assign even's next node to odd next node
        even.next = odd.next
        // move even pointer to the next node
        even = even.next
    }
    // now attach evenHead to the end of odd node
    // Why evenHead because even points to null as we loop
    odd.next = evenHead
    return head
};

Top comments (0)