My solution based on C++


  • 0
    M
    ListNode *partition(ListNode *head, int x) {
        if (NULL == head || NULL == head->next)
            return head;
            
        ListNode *pLeftHead = NULL;
        ListNode *pLeftTail = NULL;
        
        ListNode *pNode = head;
        ListNode *pPrev = NULL;
        while (NULL != pNode) {
            if (pNode->val < x) {
                if (pLeftHead == NULL) {
                    pLeftHead = pNode;
                    pLeftTail = pLeftHead;
                } else {
                    pLeftTail->next = pNode;
                    pLeftTail = pNode;
                }
                
                if (NULL == pPrev) {
                    pNode = pNode->next;
                    head = pNode;
                } else {
                    pPrev->next = pNode->next;
                    pNode = pNode->next;
                }
                
                pLeftTail->next = NULL;
            } else {
                pPrev = pNode;
                pNode = pNode->next;
            }
        }
        
        if (NULL != pLeftTail)
            pLeftTail->next = head;
        
        return (NULL == pLeftHead) ? head : pLeftHead;
    }

Log in to reply
 

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