mardi 20 octobre 2020

Odd even linked list when the number of nodes is even is not working

Im trying out a leetcode question 328. Odd even linked list. We would get in a list

1->7->3->2->4

And then need to rearrange them to link the odd placed with the odd and then add the even at the end

1 3 4 7 2

However my code, when dealing with a list of even numbers, it leaves the last even number at the end of the odd numbers

5 7 4 3 9 8 2 1

and my code rearranges it to

5 4 9 2 1 7 3 8 

but the answer should be

5 4 9 2 7 3 8 1

Im not sure why it's having this error. Below is my code

if (head->next == NULL || head->next->next == NULL)
      return head;

    ListNode *odd = head;
    ListNode *even = head->next;
    ListNode *evenHead = even;

    while (even != NULL && even->next != NULL){
      odd->next = even->next;
      odd = odd->next;
      even->next = odd->next;
      even = even->next;
    }
    odd->next = evenHead;
    return head;
}

Aucun commentaire:

Enregistrer un commentaire