148. 排序链表
在 O(n log n) 时间复杂度和常数级空间复杂度下,对链表进行排序。
示例 1:
输入: 4->2->1->3
输出: 1->2->3->4
归并排序
之前我们写过一个归并排序:LeetCode之链表排序-归并排序
采用分治的思想,先写出两个链表的合并,再进行分。。
/**
* 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(NULL==head || NULL==head->next) return head;
ListNode* pre=head,*low=head,*fast=head;
while(fast && fast->next)
{
pre=low;
low=low->next;
fast=fast->next->next;
}
pre->next=nullptr;
return addTwo(sortList(head),sortList(low));
}
ListNode* addTwo(ListNode* l1,ListNode* l2)
{
if(NULL==l1) return l2;
if(NULL==l2) return l1;
if(l1->val<l2->val)
{
l1->next=addTwo(l1->next,l2);
return l1;
}
else
{
l2->next=addTwo(l1,l2->next);
return l2;
}
}
};
插入排序
插入排序类似于向量中元素的插入排序:把待排序的结点插入到前面已经排序好的子链表中。
/**
* 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 || !head->next) return head;
ListNode* dummy=new ListNode(-1);
dummy->next=head;
ListNode* fast=head->next;
ListNode* low=head;
while(fast)
{
if(fast->val<low->val)
{
ListNode* temp=dummy;
while(temp->next->val<fast->val)
{
temp=temp->next;
}
low->next=fast->next;
fast->next=temp->next;
temp->next=fast;
fast=low->next;
}
else
{
fast=fast->next;
low=low->next;
}
}
return dummy->next;
}
};
快速排序
注意swap函数的写法,分区是非常有意思的!!
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
void swap(ListNode* p1, ListNode* p2)
{
if (p1->val == p2->val) return;
p1->val ^= p2->val;
p2->val ^= p1->val;
p1->val ^= p2->val;
}
ListNode* sortList(ListNode* head) {
QuickSort(head,NULL);
return head;
}
void QuickSort(ListNode* head,ListNode* tail)
{
if(head == tail || head->next == tail) return;
int pivot = head->val;
ListNode *left = head, *cur = head->next;
while(cur != tail)
{
if(cur->val < pivot){
left = left->next;
swap(left, cur);
}
cur = cur->next;
}
swap(head, left);
QuickSort(head, left);
QuickSort(left->next, tail);
}
};