Easy to understand and readable C++ solution. 6ms, beats 100%


  • 0
    M
    /**
     * 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) {
            ListNode *small = NULL, *large = NULL, *smallTemp = NULL, *largeTemp = NULL, *temp = head;
            while(temp) {
                if (temp -> val < x) {
                    if (!small) {
                        small = temp;
                        smallTemp = small;
                    }
                    else {
                        smallTemp -> next = temp;
                        smallTemp = smallTemp -> next;
                    }
                }
                else {
                    if(!large) {
                        large = temp;
                        largeTemp = large;
                    }
                    else {
                        largeTemp -> next = temp;
                        largeTemp = largeTemp -> next;
                    }
                }
                temp = temp -> next;
            }
            if (small && large ) {
                head = small;
                smallTemp -> next = large;
                largeTemp -> next = NULL;
                return head;
            }
            else if (!small) {
                return large;
            }
            else {
                return small;
            }
        }
    };
    

Log in to reply
 

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