插入排序(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~~
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~~
相关文章推荐
- [LeetCode147]Insertion Sort List(链表插入排序)
- LeetCode 147 Insertion Sort List(链表插入排序)
- leetcode_147题——Insertion Sort List(线性表,插入排序)
- LeetCode:Insertion Sort List//链表插入排序
- Insertion Sort List(单链表插入排序)
- LeetCode Insertion Sort List 链表的插入排序
- leetcode Insertion Sort List(链表插入排序)
- insertion-sort-list——链表、插入排序、链表插入
- Insertion Sort List 使用插入排序将链表排序
- 【LeetCode-面试算法经典-Java实现】【147-Insertion Sort List(链表插入排序)】
- 静态链表插入排序(List Insertion Sort)算法
- Insertion Sort List 链表的插入排序
- LeetCode Insertion Sort List(单链表插入排序)
- [C++]LeetCode: 126 Insertion Sort List (插入排序链表)
- 链表的插入排序 Insertion Sort List
- 173. 链表插入排序 (insertion-sort-list)(c++)----lintcode面试题之链表
- Leetcode Insertion Sort List 插入排序链表
- leetcode——Insertion Sort List 对链表进行插入排序(AC)
- 链表插入排序(insertion-sort-list)
- Insertion Sort List——链表的插入排序