您的位置:首页 > 其它

插入排序(Insertion Sort List)

2014-08-29 12:17 302 查看
问题:

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~~
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  插入排序 链表