My c++ solution


  • 12
    T

    class Solution {
    public:
    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
    B

    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
    H

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


  • 0
    T

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


  • 0
    T

    thanks for explanation


Log in to reply
 

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