链表排序
题目描述
在 O(n log n) 时间复杂度和常数级空间复杂度下,对链表进行排序。
输入: 4->2->1->3
输出: 1->2->3->4
示例 2:
输入: -1->5->3->4->0
输出: -1->0->3->4->5
来源:力扣(LeetCode)
[链接][https://leetcode-cn.com/problems/sort-list]
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
快速排序算法
// quickSort.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include<iostream>
using namespace std;
struct ListNode
{
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
int main()
{
return 0;
}
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;
}
void quickSort(ListNode* left, ListNode* right)
{
if (left == right || left == NULL || right == NULL) return;
int t = right->val;
ListNode* prev = NULL;
ListNode* cur = left;
ListNode* p = left;
while (p!=right)
{
if (p->val < t)
{
swap(cur, p);
prev = cur;
cur = cur->next;
}
p = p->next;
}
if (cur != right)
{
swap(cur,right);
cur = cur->next;
}
quickSort(left, prev);
quickSort(cur, right);
}
ListNode* sortList(ListNode* head) {
ListNode* tail = head;
while (tail != NULL && tail->next != NULL) {
tail = tail->next;
}
quickSort(head, tail);
return head;
}
};
归并排序
/**
* 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 == NULL || head->next == NULL) return head;
ListNode* prevMid;
ListNode* mid = head;
ListNode* fast = head;
while (fast&&fast->next) {
prevMid = mid;
mid = mid->next;
fast = fast->next->next;
}
prevMid->next = NULL; //断掉前后两个的连接
return merge2List(sortList(head), sortList(mid));
}
ListNode* merge2List(ListNode* p1, ListNode* p2)
{
ListNode header(-1);
ListNode *p = &header;
while (p1&&p2)
{
if (p1->val >= p2->val)
{
p->next = p2;
p2 = p2->next;
}
else
{
p->next = p1;
p1 = p1->next;
}
p = p->next;
}
p->next = p1 == NULL ? p2 : p1;
return header.next;
}
};