LeetCode 148 Sort List 链表上的归并排序和快速排序
2024-08-21 06:15:08
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;
}
};
最新文章
- centos无法正常启动,报chown: invalid user:&#39;root:root&#39;
- Nginx负载均衡配置
- /proc/sysrq-trigger的功能 介绍
- 三个重要的游标sp_cursoropen
- Opencv--HoughCircles源码剖析
- Python zxing 库解析(条形码二维码识别)
- Python学习入门基础教程(learning Python)--3.2 if-else分支语句
- android app启动过程(转)
- 根据选中不同的图元来显示不同的属性面板changePropertyPane.html
- Service使用详解
- 最实用的Android开发学习路线分享
- css3写出飘雪花特效
- Hello 博客!
- golang的定时任务
- VNC远程连接阿里云Linux服务器 图形界面
- 总结开发中使用到的npm 库
- VML元素的相关资料
- MySQL error2003错误原因以及解决方案
- oracle 远程登录
- 01-名字管理系统.py