My cpp code using two fake heads


  • 0
    C
    class Solution {
    public:
        ListNode* partition(ListNode* head, int x) 
        {
            if(!head) return NULL;
            
            ListNode fakeLT(x-1);
            ListNode* ltPtr = &fakeLT;
            
            ListNode fakeGE(x);
            ListNode* gePtr = &fakeGE;
            
            while(head)
            {
                if(head->val < x)
                {
                    ltPtr->next = head;
                    ltPtr = ltPtr->next;
                }
                else
                {
                    gePtr->next = head;
                    gePtr = gePtr->next;
                }
                
                head = head->next;
            }
            
            //!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
            gePtr->next = NULL;
            //!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
            ltPtr->next = fakeGE.next;
            return fakeLT.next;
        }
    };

Log in to reply
 

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