Sort a linked list using insertion sort.


A graphical example of insertion sort. The partial sorted list (black) initially contains only the first element in the list.
With each iteration one element (red) is removed from the input data and inserted in-place into the sorted list

Algorithm of Insertion Sort:

  1. Insertion sort iterates, consuming one input element each repetition, and growing a sorted output list.
  2. At each iteration, insertion sort removes one element from the input data, finds the location it belongs within the sorted list, and inserts it there.
  3. It repeats until no input elements remain.

Example 1:

Input: 4->2->1->3
Output: 1->2->3->4

Example 2:

Input: -1->5->3->4->0
Output: -1->0->3->4->5

链表的插入排序实现原理很简单,就是一个元素一个元素的从原链表中取出来,然后按顺序插入到新链表中,时间复杂度为 O(n2),是一种效率并不是很高的算法,但是空间复杂度为 O(1),以高时间复杂度换取了低空间复杂度,参见代码如下:

class Solution {
public:
ListNode* insertionSortList(ListNode* head) {
ListNode *dummy = new ListNode(-), *cur = dummy;
while (head) {
ListNode *t = head->next;
cur = dummy;
while (cur->next && cur->next->val <= head->val) {
cur = cur->next;
}
head->next = cur->next;
cur->next = head;
head = t;
}
return dummy->next;
}
};

Github 同步地址:

https://github.com/grandyang/leetcode/issues/147

类似题目:

Sort List

Insert into a Cyclic Sorted List

参考资料:

https://leetcode.com/problems/insertion-sort-list/

https://leetcode.com/problems/insertion-sort-list/discuss/46423/Explained-C%2B%2B-solution-(24ms)

https://leetcode.com/problems/insertion-sort-list/discuss/46420/An-easy-and-clear-way-to-sort-(-O(1)-space-)

LeetCode All in One 题目讲解汇总(持续更新中...)

最新文章

  1. TScrollBox的用法 滚动事件
  2. Java基础知识系列——数组
  3. [转载]触发ASSERT(afxCurrentResourceHandle != NULL)错误的原因
  4. HTML5&amp;CSS3经典动态表单-2
  5. Finding Nemo 分类: POJ 2015-07-11 10:11 10人阅读 评论(0) 收藏
  6. Windows 8.1 Update 2更新了什么?
  7. C语言(1+1+2+1+2+3....+n)
  8. (转)MSSQL 各个发行版本版本号以及Compact 版本号
  9. JQuery动态增加删除元素
  10. hdu 1085 Holding Bin-Laden Captive!
  11. swift 动态获取label宽度或高度
  12. Java Web学习路线图
  13. ROS(indigo) 用于机器人控制的图形化编程工具--code_it robot_blockly
  14. java 类、方法、代码块修饰式关键字总结
  15. set和multiset的用法
  16. 莫烦keras学习自修第三天【回归问题】
  17. ant 安装 网址
  18. java 路径的问题
  19. 【bzoj2194】快速傅立叶之二 FFT
  20. 百度 ueditor 1.2.0 注意事项 ,上传文件问题

热门文章

  1. 安利一波ubuntu18.04作为开发环境,极度舒适
  2. Restful服务应不应该在URI中加入版本号
  3. element-ui的tabs默认选中页签
  4. c# Equal函数 and 运算符&#39;==&#39; (原发布 csdn 2017年10月15日 20:39:26)
  5. Oracle查询日期字段是否包含时分秒 TRUNC() 函数
  6. Linux磁盘系统——磁盘系统简介
  7. swift中文版和网站
  8. Struts2 Action的3种创建方式
  9. springBoot添加日志管理
  10. 1.说一下的 dubbo 的工作原理?注册中心挂了可以继续通信吗?说说一次 rpc 请求的流程?