My c solution 68ms


  • 0
    W

    struct ListNode* insertionSortList(struct ListNode* head) {

    if(head == NULL) return head;
    if(head->next == NULL) return head;
    
    struct ListNode *temp,*pre_temp,*sorted,*pre_sorted,*swap;
    sorted = head;
    pre_temp = head;
    temp = head->next;
    
    while(temp != NULL)
    {
    	sorted = head;
        while(sorted->val <= temp->val)
        {
        	if(sorted->next == NULL )
        		return head;
    
        	pre_sorted = sorted;
        	sorted = sorted->next;
        	if(sorted == temp && sorted->next != NULL)
        	{
        		break;
        	}
        }
        // swap
        if(sorted == head)
        {
        	swap = temp;
        	temp = temp->next;
        	pre_temp->next = swap->next;
        	swap->next = sorted;
        	head = swap;
        } else if (sorted == temp)
        {
        	pre_temp = temp;
        	temp = temp->next;
        }
        else {
        swap = temp;
        temp = temp->next;
        pre_temp->next = swap->next;
        pre_sorted->next = swap;
        swap->next = sorted;
    	}
    
    }
    return head;
    

    }


Log in to reply
 

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