#include<iostream>
#include<set>
#include<vector>
#include<string>
using namespace std;
struct Node
{
int value;
Node * next;
Node(int v = 0) :value(v), next(nullptr){}
};
Node * duplicate(Node * head)
{
set<int> sets;
Node * p = head;
while (p!=nullptr&&p->next!=nullptr)
{
int v = p->next->value;
if (sets.find(v)==sets.end())
{
sets.emplace(v);
p = p->next;
}
else
{
Node * d = p->next;
p->next = d->next;
delete d;
}
}
return head;
}
void printNode(Node * head)
{
Node * p = head->next;
while (p!=nullptr&&p->next!=nullptr)
{
cout << p->value << " ";
p = p->next;
}
cout << p->value << endl;
}
void quicksort(Node* head,Node* tail)
{
if (head == tail || head->next == tail)
{
return;
}
Node* pre = head->next;
Node *temp = head->next;
Node * p = head->next->next;
while (p != tail)
{
if (p->value<=temp->value)
{
pre->next = p->next;
p->next = head->next;
head->next = p;
p = pre->next;
}
else
{
pre = p;
p = p->next;
}
}
quicksort(temp, tail);
quicksort(head, temp);
}
int main()
{
int n;
set<int> sets;
vector<int> vec;
Node * head = new Node(0);
Node * p = head;
while (cin>>n)
{
Node * temp = new Node(n);
p->next = temp;
p = temp;
}
quicksort(head, nullptr);
//head = duplicate(head);
printNode(head);
return 0;
}
下面借助图说一下基于链表的快排:
图一:temp指向基准节点,p从基准节点的下一个节点开始遍历链表,pre保存p的前一个结点。
- 当p指向的结点大于temp结点,则继续向后遍历;
- 当p指向的结点小于等于temp结点,把p指向的结点头插法到链表。之后p接着往后遍历。
程序结果图: