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

单链表排序----快排 & 归并排序

(1)归并排序

 /**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* sortList(ListNode* head) {
if (head == nullptr || head->next == nullptr)
return head;
ListNode* slow = head;
ListNode* fast = head;
ListNode* mid = nullptr;
while (fast&&fast->next)
{
mid = slow;
slow = slow->next;
fast = fast->next->next;
}
mid->next = nullptr;
return mergeHelp(sortList(head), sortList(slow));
}
ListNode* mergeHelp(ListNode* low, ListNode* high)
{
ListNode* head = new ListNode(-);
ListNode* cur = head;
while (low&&high)
{
if (low->val < high->val)
{
cur->next = low;
low = low->next;
}
else
{
cur->next = high;
high = high->next;
}
cur = cur->next;
}
cur->next = low ? low : high;
return head->next;
}
};

(2)快速排序

①.使第一个节点为中心点;
②.创建2个指针(first,second),first指向头结点,second指向first的下一个节点;
③.second开始遍历,如果发现second的值比中心点的值小,则此时first=first.next,并且执行当前first的值和second的值交换,second遍历到链表尾即可;
④.把头结点的值和first的值执行交换。此时first节点为中心点,并且完成1轮快排
⑤.使用递归的方法即可完成排序检测是否合法

 /**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* sortList(ListNode* head) {
if(head==nullptr)
return head;
quickSort(head,nullptr);
return head;
}
void quickSort(ListNode* begin,ListNode* end)
{
if(begin!=end)
{
ListNode* sep=getSeperator(begin,end);
quickSort(begin,sep);
quickSort(sep->next,end);
}
}
ListNode* getSeperator(ListNode* begin,ListNode* end)
{
ListNode* first=begin;
ListNode* second=begin->next;
int key=begin->val;
while(second!=end)
{
if(second->val<key)
{
first=first->next;
swap(first,second);
}
second=second->next;
}
swap(begin,first);
return first;
}
void swap(ListNode* a,ListNode* b)
{
int tmp=a->val;
a->val=b->val;
b->val=tmp;
}
};

最新文章

  1. centos无法正常启动,报chown: invalid user:&#39;root:root&#39;
  2. Nginx负载均衡配置
  3. /proc/sysrq-trigger的功能 介绍
  4. 三个重要的游标sp_cursoropen
  5. Opencv--HoughCircles源码剖析
  6. Python zxing 库解析(条形码二维码识别)
  7. Python学习入门基础教程(learning Python)--3.2 if-else分支语句
  8. android app启动过程(转)
  9. 根据选中不同的图元来显示不同的属性面板changePropertyPane.html
  10. Service使用详解
  11. 最实用的Android开发学习路线分享
  12. css3写出飘雪花特效
  13. Hello 博客!
  14. golang的定时任务
  15. VNC远程连接阿里云Linux服务器 图形界面
  16. 总结开发中使用到的npm 库
  17. VML元素的相关资料
  18. MySQL error2003错误原因以及解决方案
  19. oracle 远程登录
  20. 01-名字管理系统.py

热门文章

  1. MySQL Sending data导致查询很慢的问题详细分析
  2. spark提交模式
  3. Mysql 数据库时间更新字段
  4. 115个Java面试题和答案
  5. Dialog 基本使用
  6. Umbraco项目发布错误 --More than one type want to be a model for content type authorize
  7. C# 用委托有什么好处? 它起什么作用?
  8. QueryString
  9. MVC下使用ajax后台查询值赋值到前端控件
  10. 从 .NET Framework到 .NET Core