1. Sort List

Sort a linked list in O(n log n) time using constant space complexity.

Example 1:

Input: 4->2->1->3
Output: 1->2->3->4

Example 2:

Input: -1->5->3->4->0
Output: -1->0->3->4->5

解法1 归并排序。用两个函数实现:

  • merge:将两个有序链表合在一起
  • merge_sort:将无序链表排序

找中间位置用双指针

/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
ListNode* sortList(ListNode* head) {
if(head == NULL || head->next == NULL)return head;
ListNode *mid, *pre;
find_mid(head, mid, pre);
pre->next = NULL;
return merge(sortList(head), sortList(mid));
}
// 找中点时,需要对mid和pre做修改,因此需要传引用
void find_mid(ListNode* s, ListNode* &mid, ListNode* &pre){
ListNode *pp = s;
mid = s;
while(pp && pp->next){
pre = mid;
mid = mid->next;
pp = pp->next->next;
}
}
ListNode* merge(ListNode* s1, ListNode* s2){
ListNode *head = new ListNode, *p = s1, *q = s2;
ListNode *cur = head;
while(p != NULL && q != NULL){
if(p->val < q->val){
cur->next = p;
p = p->next;
}else{
cur->next = q;
q = q->next;
}
cur = cur->next;
}
if(p != NULL)cur->next = p;
else cur->next = q;
return head->next;
}
};

解法2 快速排序。partition过程中,可以用两个链表small和large分别存储pivot左侧和右侧的数据

class Solution {
public:
ListNode* sortList(ListNode* head) {
if(!head || !head->next) return head; ListNode* cur = head->next;
ListNode* small = new ListNode(0);
ListNode* large = new ListNode(0);
ListNode* sp = small;
ListNode* lp = large;
// partition
while(cur){
if(cur->val<head->val){
sp->next = cur;
sp = cur;
}
else{
lp->next = cur;
lp = cur;
}
cur = cur->next;
}
sp->next = NULL;
lp->next = NULL;
small=sortList(small->next);
large=sortList(large->next);
cur = small;
if(cur){
while(cur->next) cur = cur->next;
cur->next = head;
head->next = large;
return small;
}else{
head->next = large;
return head;
}
}
};

最新文章

  1. Javascript刷题 》数组求和
  2. C#的继承
  3. 机器数据的价值 - Web 访问日志和数据库审计日志
  4. 首次安装Pycharm出现No Python interpreter selected解决方法
  5. JS 模板引擎之JST模板
  6. ServletContext中常用方法(getRsource和getResourceAsStream)
  7. tinyhttpd服务器源码学习
  8. Linux下Sublime Text 2的安装
  9. Hadoop集群(第2期)_机器信息分布表
  10. 转:C++ 性能测试支持
  11. .Net4.0如何实现.NET4.5中的Task.Run及Task.Delay方法
  12. Android设置背景
  13. Python-re模块中一些重要函数
  14. socket之黏包
  15. spring静态代理和动态代理
  16. JavaScript 加解密库(crypto-js)
  17. springcloud如何实现服务的平滑发布
  18. RNA提取和建库流程对mRNA-Seq的影响
  19. Image Processing in Python with Pillow
  20. STlinkSWD模式连线方式

热门文章

  1. 一篇文章讲明白vue3的script setup,拥抱组合式API!
  2. [Elasticsearch] ES 的Mapping 设计在实际场景中应用
  3. Linux(Centos) 设置显示vim行号
  4. Linux(centos)下修改mysql的sql_mode模式
  5. JAVA判断是否是微信内置浏览器,是否是在微信内打开
  6. Python处理utf-8 添加和删除BOM头
  7. light oj 1100 - Again Array Queries(暴力,鸽巢原理)
  8. 1269 - Consecutive Sum
  9. Codeforces 567D:One-Dimensional Battle Ships(二分)
  10. Codeforces 1073D:Berland Fair(模拟)