[LeetCode] Insertion Sort List
2015-06-25 16:14
344 查看
Sort a linked list using insertion sort.
Hide Tags
Linked List Sort
分析:把链表分成两部分:排好序的和为排序的,排好序的以NULL结尾,cur插在preInsertion和insertion之间,next保存cur->next.
另外,注意dummy的使用简化了插入头结点的情况。
时间复杂度O(n^2),空间O(1)
Hide Tags
Linked List Sort
分析:把链表分成两部分:排好序的和为排序的,排好序的以NULL结尾,cur插在preInsertion和insertion之间,next保存cur->next.
另外,注意dummy的使用简化了插入头结点的情况。
时间复杂度O(n^2),空间O(1)
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ class Solution { public: ListNode* insertionSortList(ListNode* head) { if(head == NULL) return NULL; ListNode dummy(INT_MIN); dummy.next = head; ListNode* preInsertion = NULL; ListNode* insertion = NULL; ListNode* cur = head->next; head->next = NULL;//break the sorted and unsorted ListNode* next = NULL; while(cur) { preInsertion = & dummy; insertion = dummy.next; //find the right position while(insertion != NULL && cur->val >= insertion->val) { preInsertion = preInsertion->next; insertion = insertion->next; } #if 0 if(insertion == NULL)//cur is max, don't need to move it { next = cur->next;//just store cur first; preInsertion->next = cur; cur->next = NULL; cur = next; } else { next = cur->next;//just store cur first; preInsertion->next = cur; cur->next = insertion; cur = next; } #endif next = cur->next;//just store cur first; preInsertion->next = cur; cur->next = insertion; cur = next; } return dummy.next; } };
相关文章推荐
- C# 里用到的scalar variable
- Oracle中ROWNUM的使用技巧
- CloudXNS首次使用体验
- leetcode-22Generate Parentheses
- av_register_all,avcodec_register_all的源码分析
- 每天一道算法题(24)——自定义幂函数pow
- 每天一道算法题(24)——自定义幂函数pow
- 编程资料合集
- SQL-Server 创建数据库,创建表格
- Python中的WSGI
- iOS控件之UILbel篇
- LintCode 两个链表的和
- viewpager实现无限轮播的两种方式总结
- EM算法
- 数据结构《21》----2014 WAP 第一个问题----Immutable queue
- hdu 4972 A simple dynamic programming problem(高效)
- Objective-C该Protocol
- Coreseek:部门查询和增量索引代替实时索引
- mac boot2docker certs not valid with 1.7
- 【LeetCode】LRU Cache 解决报告