My c++ solution

  • 12

    class Solution {
    ListNode* oddEvenList(ListNode* head) {

        if(head == NULL || head->next == NULL)
            return head;
        ListNode *odd = head;
        ListNode *even_head = head->next;
        ListNode *even = even_head;
        while(even != NULL && even->next != NULL)
            odd->next = even->next;
            odd = odd->next;
            even->next = odd->next;
            even = even->next;
        odd->next = even_head;
        return head;


  • 2

    separate the list to two lists--odd and even list.Then build the two lists respectively.At last, connect the even list to the end of the odd list.

  • 0

    maybe you don't need to evaluate whether head->next is NULL in the first line?

  • 0

    yes you are right....just for the sake of dealing base case I wrote the line so that no even odd nodes come in fact I prefer (!head || !head->next || !head->next->next) return head; if given input is your answer better return rather than computation

  • 0

    thanks for explanation

Log in to reply

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.