Clean simple C solution


  • 0
    H
    /**
     * Definition for singly-linked list.
     * struct ListNode {
     *     int val;
     *     struct ListNode *next;
     * };
     */
    struct ListNode* getTail(struct ListNode* head) {
        if(head == NULL || head->next == NULL) {
            return head;
        }
        
        while(head->next != NULL) {
            head = head->next;
        }
        
        return head;
    } 
     
    struct ListNode* partition(struct ListNode* head, int x) {
        struct ListNode* newList = NULL;
        struct ListNode* newHead = NULL;
        struct ListNode* node = head;
        struct ListNode* prev = NULL;
        
        if(head == NULL || head->next == NULL) {
            return head;
        }
        
        while(node != NULL) {
            //insert to new list
            struct ListNode* next = node->next;
            if(node->val >= x) {
                if(prev != NULL) {
                    prev->next = node->next;
                }
                else {
                    head = node->next;
                }
                node->next = NULL;
                if(newList == NULL) {
                    newList = node;
                    newHead = newList;
                }
                else {
                    newList->next = node;
                    newList = node;
                }
            }
            else {
                prev = node;
            }
            
            node = next;
        }
        
        struct ListNode* tail = getTail(head);
        if(tail != NULL) {
            tail->next = newHead;
        }
        else {
            head = newHead;
        }
        
        return head;
    }

Log in to reply
 

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