问题:
Sort a linked list using insertion sort.
解析:
由于上一篇已经写了对list的快排和堆排序,所以插入排序很容易上手。直接上代码吧
ListNode *insertionSortList(ListNode *head) {
if(head == NULL || head->next == NULL) return head;
ListNode *sorthead = head, *insertnode = head->next, *listnext;
sorthead->next = NULL;
while(insertnode != NULL)
{
listnext = insertnode->next; //注意保留next
if(insertnode->val < sorthead->val) //链表头处理
{
insertnode->next = sorthead;
sorthead = insertnode;
}
else
{
ListNode *per= sorthead, *now = per->next;
while(now != NULL) //找插入位置
{
if(now->val >= insertnode->val)
break;
per = now;
now = now->next;
}
per->next = insertnode;
insertnode->next = now;
}
insertnode = listnext;
}
return sorthead;
}
说明:1.对链表的插入排序比对数组的插入排序效率高~因为不用将原有数据后移来空出位置
2.对链表头需要特殊处理,思路清晰些很容易,注意初始化sorthead->next = NULL,否则会死循环
嘻嘻~继续加油!!oj~~