题目:
Sort a linked list using insertion sort.
class Solution {
public:
ListNode *insertionSortList(ListNode *head)
{
if (head == NULL || head->next == NULL) return head;
//设置当前遍历指针
ListNode * current = head->next;
head->next = NULL;//插入排序,head第一个元素就已经排好序
ListNode dummy(INT_MIN); dummy.next = head;//小技巧,方便处理
while (current != NULL)
{
insert(&dummy, current);//循环插入,时间复杂度O(n2)
}
return dummy.next;
}
//插入node到list中,并且设置node为下一个节点
void insert(ListNode * list, ListNode * & node)
{
if (node == NULL) return;
//查找插入位置
while (list->next != NULL)
{
if (list->next->val >= node->val)
break;//查找合适的位置
list = list->next;
}
//这四行代码顺序很重要
ListNode * next = list->next;
list->next = node;
node = node->next;
list->next->next = next;
return;
}
};