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 =
    let evenHead = even

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

Top comments (0)