[Leetcode]Insertion Sort List
2015-10-23 13:47
441 查看
Sort a linked list using insertion sort.
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
/*algorithm : insert sort
*/
ListNode* insertionSortList(ListNode* head) {
ListNode* nh = NULL,*p = head,*next;
while(p){
next = p->next;
//search insert pos in sorted list
ListNode* q = nh,*prev=NULL;
while(q && q->val <= p->val){
prev = q;
q = q->next;
}
if(!prev){
p->next = q;
nh = p;
}else{
prev->next = p;
p->next = q;
}
p = next;
}
return nh;
}
};
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
/*algorithm : insert sort
*/
ListNode* insertionSortList(ListNode* head) {
ListNode* nh = NULL,*p = head,*next;
while(p){
next = p->next;
//search insert pos in sorted list
ListNode* q = nh,*prev=NULL;
while(q && q->val <= p->val){
prev = q;
q = q->next;
}
if(!prev){
p->next = q;
nh = p;
}else{
prev->next = p;
p->next = q;
}
p = next;
}
return nh;
}
};
相关文章推荐
- Camera Calibration 相机标定:原理简介(四)
- javascript贪吃蛇小游戏
- APP测试体系
- hdu 1576(A/B)
- Camera Calibration 相机标定:原理简介(四)
- 多附件上传
- Labview 中的类
- [转] 再探java基础——break和continue的用法
- SharePoint 2007 IT Professional --如何进行Search Content?
- android adb常用指令
- gc buffer busy acquire vs release
- js特效——闪电
- HDU 2475 Box [dfs序+splay]
- jxl.write.biff.RowsExceededException: The maximum number of rows permitted on a worksheet been excee
- Linux搭建vsftp
- Boost源码学习二[内存管理一]下
- 【程序员眼中的统计学(8)】统计抽样的运用:抽取样本
- idea快捷键
- Centos7安装MySQL常见问题
- BosonNLP分词技术解密