147. Insertion Sort List
来源:互联网 发布:爱淘宝怎么删除 编辑:程序博客网 时间:2024/06/16 02:51
这道题要求用插入排序法给一个链表排序。
这道题我写的很麻烦,但是一次就AC了。我维护两个链表,一个是已经排好了的一部分,一个是待排序的一部分。然后把待排序的那部分一个个插入。
/** * 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* pre = NULL, *tail = NULL, *cur = head; while(cur){ if(pre == NULL){ pre = cur; tail = cur; cur = cur->next; tail->next = NULL; }else{ if(cur->val >= tail->val){ tail->next = cur; tail = cur; cur = cur->next; tail->next = NULL; }else if(cur->val <= pre->val){ ListNode* curnext = cur->next; cur->next = pre; pre = cur; cur = curnext; }else{ ListNode* insert = pre; while(insert->next->val < cur->val){ insert = insert->next; } ListNode* insertnext = insert->next; ListNode* curnext = cur->next; insert->next = cur; cur->next = insertnext; cur = curnext; } } } return pre; }};看别人的简单的代码:
/** * 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) { ListNode *res = new ListNode(-1); ListNode *cur = res; while (head) { ListNode *next = head->next; cur = res; while (cur->next && cur->next->val <= head->val) { cur = cur->next; } head->next = cur->next; cur->next = head; head = next; } return res->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
- 正则
- Mysql 服务无法启动 服务没有报告任何错误
- ⑨ NDK学习之C语言IO
- shder总结四
- mysql数据导入到数据库
- 147. Insertion Sort List
- Servlet总结
- 小知识点
- KafkaController介绍
- 30秒看懂UML类图
- ubuntu 14.04 安装 open-vm-tools失败
- Java中自动拆装箱
- 在session对象当中无法进行属性值参数的获取
- SVN + Maven + jenkins 实现自动化构建