C++ One Pass Solution using O(n) Time and O(1) Space


  • 0
    Y
    /**
     * 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)
                return head;
            ListNode *odd = head, *even = NULL;
            even = odd->next;
            if(!even)
                return head;
            ListNode *step = NULL, *p, *q;
            step = even->next;
            q = even;
            p = head;
            while(step){
                p->next = step;
                step = step->next;
                q->next = step;
                if(step){
                    step = step->next;
                }
                p = p->next;
                q = q->next;
            }
            p->next = even;
            return head;
        }
    };

Log in to reply
 

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