记录一下单链表快排的写法,直接上代码:
#include<iostream>
#include <ctime>
using namespace std;
struct Node {
int val;
Node* next;
Node(int v) : val(v), next(nullptr) {}
};
void NodeSwap(Node* a, Node* b) {
int tmp = a->val;
a->val = b->val;
b->val = tmp;
}
Node* partition(Node* st, Node* ed) {
Node* p = st;
Node* q = st->next;
int key = p->val;
while (q != ed) {
if (q->val < key) {
p = p->next;
NodeSwap(p, q);
}
q = q->next;
}
NodeSwap(st, p);
return p;
}
void NodeQuickSort(Node* st, Node* ed) {
if (st != ed) {
Node* part = partition(st, ed);
NodeQuickSort(st, part);
NodeQuickSort(part->next, ed);
}
}
Node* CreateList(int n) {
if (!n) return nullptr;
int val = rand();
Node* root = new Node(val);
Node* p = root;
for (int i = 1; i < n; ++i) {
val = rand();
p->next = new Node(val);
p = p->next;
}
return root;
}
void PrintList(Node* root) {
if (!root) return;
cout << root->val;
root = root->next;
while (root) {
cout << " -> " << root->val;
root = root->next;
}
cout << endl;
}
int main() {
srand((unsigned int)time(nullptr));
Node* root = CreateList(10);
cout << "before" << endl;
PrintList(root);
cout << "after" << endl;
NodeQuickSort(root, nullptr);
PrintList(root);
return 0;
}