LintCode 链表插入排序
2015-06-25 15:19
363 查看
用插入排序对链表排序
样例
Given 1->3->2->0->null, return 0->1->2->3->null
Sort a linked list using insertion sort.
Example
Given 1->3->2->0->null, return 0->1->2->3->null.
样例
Given 1->3->2->0->null, return 0->1->2->3->null
Sort a linked list using insertion sort.
Example
Given 1->3->2->0->null, return 0->1->2->3->null.
/** * Definition for ListNode. * public class ListNode { * int val; * ListNode next; * ListNode(int val) { * this.val = val; * this.next = null; * } * } */ public class Solution { /** * @param head: The first node of linked list. * @return: The head of linked list. */ public ListNode insertionSortList(ListNode head) { if(null == head|| null == head.next) return head; ListNode newhead = head; head = head.next; newhead.next = null; ListNode q = newhead, p = head; while(null != p) { ListNode r = p.next; if(q.val >= p.val) {//插在头部 p.next = q; newhead = p; q = p; p = r; continue; } while(null != q.next) {//插在中间 if(q.val < p.val && q.next.val >= p.val) { p.next = q.next; q.next = p; } q = q.next; } if(q.val < p.val) {//插在尾部 q.next = p; p.next = null; } p = r; q = newhead; } return newhead; } }
相关文章推荐
- SQL 入门笔记
- Python用PyInstaller打包笔记
- MySQL中distinct及group by的一些用法
- HTML5移动开发常用meta标签
- 感知机 perceptron
- 蓝牙4.0 BLE 模块问答
- You need to use a Theme.AppCompat theme (or descendant) with this activity.
- IP和端口号的关系
- ORACLE RMAN增量备份经典理解
- Mac下jdk的安装路径
- hibernate 映射关系—关系映射(一对一)
- MySQL中distinct及group by的一些用法
- jiffies溢出与时间先后比较-time_after,time_before
- Winform系列——好看的DataGridView折叠控件
- 封装保存、下载图片到本地的方法记录
- hibernate 中id生成策略
- 內表数据导出到EXCEL文件中
- Cocos2dx------详细介绍如何编写扫雷这个游戏含源码(一)
- 类模板和函数模板引发的思考
- C语言文件操作