147. Insertion Sort List
来源:互联网 发布:潜韵耳机的官方淘宝店 编辑:程序博客网 时间:2024/04/27 03:04
Sort a linked list using insertion sort.
题意:对链表进行插入排序。
思路:每次对tail之后的结点操作,并适当更新tail(或head)。
class Solution {public:ListNode* insertionSortList(ListNode* head) {if (head == NULL)return head;ListNode* tail = head;ListNode* q = tail->next;while (q){//extracttail->next = q->next;//searchListNode* tmp = head;if (tmp->val >= q->val){q->next = tmp;head = q;}else{while (tmp != tail && tmp->next->val < q->val){tmp = tmp->next;}q->next = tmp->next;tmp->next = q;if (tmp == tail)tail = q;}//go onq = tail->next;}return head;}};
二刷:链表的操作,设置一个dummy会好一些。插入排序,不能从后向前走,因为链表是单向的,所以每次要从头往后找。因此设置一个dummy就会方便很多。
class Solution {public:ListNode* insertionSortList(ListNode* head) {ListNode *dummy = new ListNode(0);ListNode *cur = head;while (cur){ListNode *tmp = cur->next;insert(dummy, cur);cur = tmp;}return dummy->next;}private:void insert(ListNode *dummy, ListNode* cur){ListNode *pre = dummy;while (pre->next && pre->next->val < cur->val)pre = pre->next;ListNode *tmp = pre->next;pre->next = cur;cur->next = tmp;}};
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
- PxCook像素大厨,UI设计师标注切图的利器
- c#调用带out类型参数的存储过程拿不到返回值的解决办法
- java实现汉字字典
- 玩转MediaPlayer
- 学习WCF之路1:Hello WCF!
- 147. Insertion Sort List
- git 创建远程仓库并将本地文件上传到远程仓库
- GitHub及Git的使用
- 微信开发常用文档及参考资料
- python 连接各类主流数据库简单示例
- Spring线程池配置
- 致贺
- ROS_Kinetic_14 ROS工具roswtf的基本使用方法等
- 16:反转链表