147. Insertion Sort List
来源:互联网 发布:vb.net 表格控件 编辑:程序博客网 时间:2024/03/29 21:20
Sort a linked list using insertion sort.
建议:为了操作方便,添加一个额外的头结点。代码如下:
class Solution {public: ListNode* insertionSortList(ListNode* head) { if(head==NULL||head->next==NULL) return head; ListNode* fakeHead=new ListNode(0), *p, *cur=head, *next, *pre; fakeHead->next=head; cur=head->next; pre =head; while (cur) { next=cur->next; if (cur->val>=pre->val) { pre=cur; cur=next; } else { pre->next=next; p = fakeHead; while (p->next->val<cur->val) { p = p->next; } cur->next=p->next; p->next=cur; cur=next; } } p = fakeHead->next; delete fakeHead; return p; } };
15.9.20更新
------------------
思路:
拿出原list的头节点,用一个指针扫描新list直到找到插入位置,并插入。注意点:
1. 用dummy head来简化新list的头节点操作。
2.由于插入节点需要依赖插入位置的前一节点。所以用指针p来查找新list节点时,始终用p->next来和要插入的节点比较,而不是用p来比较。
3. 注意当节点需要插入新list尾部的情况。
代码如下:
class Solution {public: ListNode *insertionSortList(ListNode *head) { ListNode *newHead = new ListNode(INT_MIN); while(head) { ListNode *cur = head; ListNode *p = newHead; head = head->next; while(p->next && p->next->val<=cur->val) p = p->next; cur->next = p->next; p->next = cur; } head = newHead->next; delete newHead; return head; }};
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
- Android开发圆角button的简单实现
- 用AFNetworking 调用新浪发微博的API
- 题目:A + B 问题
- Spring-Component注解翻译
- iOS 笔记二:Multiple MVCs 、UINavigationController 、UITabBarController
- 147. Insertion Sort List
- 有关Apache Ignite的peer class loading (P2P class loading)
- javascript开发与调试方法
- Linux下随机10字符病毒的清除
- 题目:k数和 II
- HDU 1015 Safecracker(DFS搜索)
- MYSQL5.X重置root密码 (windows系统)
- SpringMVC简单构造restful, 并返回json——(一)
- 题目:Maximal Square