6ms C++ solution


  • 0
    X
    class Solution {
    public:
        /**
         * @param head: The first node of linked list.
         * @param x: an integer
         * @return: a ListNode 
         */
        ListNode *partition(ListNode *head, int x) {
            ListNode *lhead = NULL, *ltail = NULL;
            ListNode *ghead = NULL, *gtail = NULL;
            while (head) {
                if (head->val < x) {
                    if (!lhead)
                        lhead = ltail = head;
                    else {
                        ltail->next = head;
                        ltail = ltail->next;
                    }
                } else {
                    if (!ghead)
                        ghead = gtail = head;
                    else {
                        gtail->next = head;
                        gtail = gtail->next;
                    }
                }
                head = head->next;
            }
            if (gtail)
                gtail->next = NULL;
            if (ltail) {
                ltail->next = ghead;
                return lhead;
            }
            return ghead;
        }
    };
    
    

Log in to reply
 

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