147. Insertion Sort List
2016-04-10 20:48
405 查看
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ //80 ms class Solution { public: ListNode* insertion(ListNode* temp,ListNode* head) { if(temp->val<head->val) { temp->next=head; return temp; } ListNode* a=head; while(a->next&&a->next->val<temp->val) a=a->next; if(!a->next) { temp->next=NULL; a->next=temp; } else { temp->next=a->next; a->next=temp; } return head; } ListNode* insertionSortList(ListNode* head) { if(!head) return head; ListNode* temp1=head->next; ListNode* head0=head; head0->next=NULL; while(temp1) { ListNode* temp=temp1->next; head0=insertion(temp1,head0); temp1=temp; } return head0; } };
//80ms class Solution { public: ListNode* insertionSortList(ListNode* head) { if(!head) return head; ListNode myhead(INT_MIN),*cur,*temp; while(head) { for(cur=&myhead;cur->next&&cur->next->val<head->val;) cur=cur->next; temp=head->next; head->next=cur->next; cur->next=head; head=temp; } return myhead.next; } };
//24ms //即使是插入排序,也不需要每次都从头查找 class Solution { public: ListNode* insertionSortList(ListNode* head) { if(!head) return head; ListNode myhead(INT_MIN),*cur=&myhead,*temp; while(head) { if(head->val<cur->val) cur=&myhead; for(;cur->next&&cur->next->val<head->val;) cur=cur->next; temp=head->next; head->next=cur->next; cur->next=head; head=temp; } return myhead.next; } };
相关文章推荐
- HDU 1074 Doing Homework
- LeetCode *** 125. Valid Palindrome
- 关于hibernate使用log4j
- linux ssh -l 命令运用
- 网络基本功系列:细说交换机
- 数据库下载
- [置顶] MySQL5.7.9安装
- 快速排序的实现(两种)
- 【数位DP】[CQOI2016]手机号码
- Centos7 Ansible安装
- libcudnn.so.6.5:cannot open sharedobject file: No such file or directory
- 谁是真泛型
- Android - 十分钟理解手机适配 与 lib工程生成包
- 第六周进度报告
- 第四次作业
- 排序注意事项
- 常用的布局和View常用属性
- Eclipse更改主题,换个黑色的背景颜色吧,哈哈
- Ubuntu14.04安装nodejs
- 数据库的恢复