两种写法,一个是换数值,一个是换链表
#include<bits/stdc++.h>
using namespace std;
struct ListNode
{
int val;
ListNode *next;
ListNode(int _val)
{
val = _val;
next = nullptr;
}
};
ListNode* partition(ListNode *head, ListNode *tail)
{
ListNode *pos = head;
// int key = head->val;
for(ListNode *i = head->next; i!=tail; i=i->next)
{
if(i->val < head->val)
{
pos = pos->next;
swap(i->val, pos->val);
}
}
swap(head->val, pos->val);
return pos;
}
//左闭右开区间,只换数值,不换链表
ListNode* quickSortList(ListNode *head, ListNode *tail)
{
if(head==nullptr || head->next==nullptr)
return head;
if(head == tail || head->next == tail)
return head;
// cout<<"begin"<<endl;
// ListNode *temp = head;
// while(temp!=tail)
// {
// cout<<temp->val<<" ";
// temp = temp->next;
// }
// cout<<endl;
ListNode* pos = partition(head, tail);
// cout<<pos->val<<endl;
// system("pause");
// cout<<"head val = "<<head->val<<endl;//<<", tail val = "<<tail->val<<endl;
quickSortList(head, pos);
// cout<<"fff"<<endl;
quickSortList(pos->next, tail);
return head;
}
ListNode* partition2(ListNode *pre, ListNode *head, ListNode *tail )
{
// ListNode *pos = head;
// int key = head->val;
ListNode little(0);
ListNode big(0);
ListNode *pl = &little, *pb = &big;
for(ListNode *i = head->next; i!=tail; i=i->next)
{
if(i->val < head->val)
{
pl->next = i;
pl = pl->next;
}
else
{
pb->next = i;
pb = pb->next;
}
}
//一定注意顺序!不然little.next或者big.next为空时会出问题
pl->next = head;
pb->next = tail;
head->next = big.next;
pre->next = little.next;
return head;
}
//直接换链表的方式
ListNode* quickSortList2(ListNode *pre, ListNode *head, ListNode *tail)
{
if(head==nullptr || head->next==nullptr)
return head;
if(head == tail || head->next == tail)
return head;
// cout<<"begin"<<endl;
ListNode* pos = partition2(pre, head, tail);
// cout<<pos->val<<endl;
// ListNode *temp = pre->next;
// while(temp!=nullptr)
// {
// cout<<temp->val<<" ";
// temp = temp->next;
// }
// cout<<endl;
// system("pause");
// cout<<"head val = "<<head->val<<endl;//<<", tail val = "<<tail->val<<endl;
quickSortList2(pre, pre->next, pos);
quickSortList2(pos, pos->next, tail);
// cout<<pre->next->val<<endl;
return pre->next;
}
int main()
{
ListNode *head = new ListNode(10);
ListNode *node = head;
node->next = new ListNode(8);
node->next->next = new ListNode(9);
node->next->next->next = new ListNode(1);
node->next->next->next->next = new ListNode(7);
node->next->next->next->next->next = new ListNode(4);
// quickSortList(head, nullptr);
// while(head!=nullptr)
// {
// cout<<head->val<<" ";
// head = head->next;
// }
// cout<<endl;
ListNode *tmp = new ListNode(0);
tmp->next = head;
ListNode *newhead = quickSortList2(tmp , head, nullptr);
// cout<<newhead->val<<endl;
while(newhead!=nullptr)
{
cout<<newhead->val<<" ";
newhead = newhead->next;
}
cout<<endl;
}