Super simple O(N) C++ solution


  • 0
    E
    /**
     * Definition for singly-linked list.
     * struct ListNode {
     *     int val;
     *     ListNode *next;
     *     ListNode(int x) : val(x), next(NULL) {}
     * };
     */
    class Solution
    {
    public:
        ListNode *partition(ListNode *head, int x)
        {
            if (!head) return head;
    
            ListNode *headA = new ListNode(0);
            ListNode *headB = new ListNode(0);
            ListNode *tailA = headA;
            ListNode *tailB = headB;
    
            while (head != nullptr)
            {
                if (head->val < x)
                {
                    tailA->next = new ListNode(head->val);
                    tailA = tailA->next;
                }
                else
                {
                    tailB->next = new ListNode(head->val);
                    tailB = tailB->next;
                }
    
                head = head->next;
            }
    
            tailA->next = headB->next;
    
            return headA->next;
        }
    };

  • 0
    T

    You don't need to copy the node with new ListNode, just use = head; the only thing needs taking care of is actually separating the two paritions, to make sure there are no cycles: tailB->next = nullptr.


Log in to reply
 

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