Straightforward c++ code, o(n) time, O(1) space, one pass


  • 0
    S
    class Solution {
    public:
        ListNode* oddEvenList(ListNode* head) {
            ListNode *odd = head;
            if(!odd) return NULL;
            ListNode *evenhead = new ListNode(0);
            ListNode *even = odd->next;
            evenhead->next = even;
            while(odd->next&&even->next)
            {
                odd->next = even->next;
                odd = odd->next;
                even->next = odd->next;
                even = even->next;
            }
            odd->next = evenhead->next;
            return head;
        }
    };

Log in to reply
 

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