时间复杂度O(N*logN),空间复杂度O(1)
参考 http://www.cnblogs.com/TenosDoIt/p/3666585.html
//依据快速排序METOHD_3的思想
//取第一个元素作为枢纽元
//链表范围是[low, high)
#include <iostream>
using namespace std;
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
void swap(int &a, int &b){
int tmp = a;
a = b;
b = tmp;
}
ListNode *partition(ListNode *head, ListNode *tail){
//链表范围是[low, high)
ListNode *mid = head;
for (ListNode *p = head->next; p != tail; p = p->next){
if (p->val < head->val){
mid = mid->next;
if (mid != p){
swap(mid->val, p->val);
}
}
}
swap(mid->val, head->val);
return mid;
}
void quick_sort(ListNode *head, ListNode *tail){
//链表范围是[low, high)
if (head == tail || head->next == tail)
return;
ListNode *mid = partition(head, tail);
quick_sort(head, mid);
quick_sort(mid->next, tail);
}
ListNode *quick_sort_list(ListNode *head){
//链表范围是[low, high)
if (head == NULL || head->next == NULL)
return head;
quick_sort(head, NULL);
return head;
}
int main(){
ListNode *head = new ListNode(0);
ListNode *node1 = new ListNode(3);
ListNode *node2 = new ListNode(1);
ListNode *node3 = new ListNode(2);
ListNode *node4 = new ListNode(6);
ListNode *node5 = new ListNode(5);
ListNode *node6 = new ListNode(4);
head->next = node1;
node1->next = node2;
node2->next = node3;
node3->next = node4;
node4->next = node5;
node5->next = node6;
ListNode *p = head;
while(p){
cout << p->val << '\t';
p = p->next;
}
cout << endl;
ListNode *result = quick_sort_list(head);
p = result;
while(p){
cout << p->val << '\t';
p = p->next;
}
cout << endl;
int ttt = 0;
return 0;
}