147. Insertion Sort List
来源:互联网 发布:淘宝联盟手机怎么登陆 编辑:程序博客网 时间:2024/04/23 17:36
方法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||head->next==NULL) return head; ListNode* Head=new ListNode(-1); ListNode* pre=Head; ListNode* cur=head->next; ListNode* nx=NULL; head->next=pre; pre=head; while(cur) { nx=cur->next; if(pre->val<=cur->val) { cur->next=pre; pre=cur; } else { ListNode* p=pre; while(pre->next!=Head&&pre->next->val>cur->val) { pre=pre->next; } cur->next=pre->next; pre->next=cur; pre=p; } cur=nx; } cur=pre->next; pre->next=NULL; while(cur) { nx=cur->next; cur->next=pre; pre=cur; cur=nx; } return Head->next; }};
方法2:
从前往后比较
class Solution {public: ListNode* insertionSortList(ListNode* head) { if(head==NULL||head->next==NULL) return head; ListNode* Head=new ListNode(-1); ListNode* cur=head; while(cur) { ListNode* nx=cur->next; ListNode* pre=Head; while(pre->next&&pre->next->val<cur->val) { pre=pre->next; } cur->next=pre->next; pre->next=cur; cur=nx; } return Head->next; }};
0 0
- 147. Insertion Sort List
- 147. Insertion Sort List
- 147. Insertion Sort List
- 147. Insertion Sort List
- 147. Insertion Sort List
- 147. Insertion Sort List
- 147. Insertion Sort List
- 147. Insertion Sort List
- 147. Insertion Sort List
- 147. Insertion Sort List
- 147. Insertion Sort List
- 147. Insertion Sort List
- 147. Insertion Sort List
- 147. Insertion Sort List
- 147. Insertion Sort List
- 147. Insertion Sort List
- 147. Insertion Sort List
- 147. Insertion Sort List
- Zookeeper 介绍 Zookeeper 搭建 Zookeeper 集群搭建
- iOS一分钟搞定加入购物车的交互动画
- JSON与JSONObject解析json数据
- 数据库
- 回归博客
- 147. Insertion Sort List
- vi 一般模式下常用命令
- C++底层数据结构的实现原理
- Filezilla无法确定拖放操作目标,由于shell未正确安装__解决办法
- JQuery函数大全
- Codeforces 707B Bakery(最短路)
- 数组合并System.arraycopy
- 重新回去ubuntu做事了,遇到问题
- 安利一波gif录制工具