[LeetCode] Insertion Sort List

ListNode *insertionSortList(ListNode *head) {
	if(head == NULL)
	{
		return head;
	}
	ListNode * sorted_list = new ListNode(0);
	sorted_list->next = head;
	ListNode* unsorted_list = head->next;
	head->next = NULL;
	while(unsorted_list != NULL)
	{
		ListNode* unsorted_node = unsorted_list;
		unsorted_list = unsorted_node->next;           
		ListNode* pre_node = sorted_list;
		ListNode* cur_node = sorted_list->next;
 		while(cur_node != NULL)
		{
			if(unsorted_node->val < cur_node->val)
			{
				pre_node->next = unsorted_node;
				unsorted_node->next = cur_node;
				break;
			}
			else if(cur_node->next == NULL)
			{
				cur_node->next = unsorted_node;
				unsorted_node->next = NULL;
			}   
			pre_node = pre_node->next;
			cur_node = cur_node->next;
		}                   
	}
	sorted_list = sorted_list->next;
	return sorted_list;
}

你可能感兴趣的:(LeetCode,刷题)