Sharing my 20ms C++ solution


  • 2
    T
    /**
     * Definition for singly-linked list.
     * struct ListNode {
     *     int val;
     *     ListNode *next;
     *     ListNode(int x) : val(x), next(NULL) {}
     * };
     */
    class Solution {
    public:
        ListNode* oddEvenList(ListNode* head) {
            if(head==NULL || head->next==NULL)
                return head;
            ListNode* odd = head;
            ListNode* even = head->next;
            
            ListNode* pOdd = odd;
            ListNode* pEven = even;
            
            while(true)
            {
                if(pEven->next)
                {
                    pOdd->next = pEven->next;
                    pOdd = pOdd->next;
                }
                else
                    break;
                    
                if(pOdd->next)
                {
                    pEven->next = pOdd->next;
                    pEven = pEven->next;
                }
                else
                    break;
            }
            
            pOdd->next = even;
            pEven->next = NULL;
            return odd;
        }
    };

  • 0
    M

    I had a similar solution. There is still a run-time error however when an empty linked list is passed


Log in to reply
 

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