写了大半天,终于折腾出了这个难看的链表快速排序:
#include <iostream>
#include <iterator>
#include <algorithm>
using namespace std;
int array[] = {1, 2, 3, 3, 3, 3, 4, 5, 6, 7, 6, 5, 4, 3, 2, 1, 0};
const int size = sizeof array / sizeof *array;
struct Node
{
Node(int i = 0, Node *n = NULL) : data(i), next(n) {}
int data;
Node *next;
};
Node *construct()
{
Node *head = NULL;
Node *pHead = head;
for (int i = 0; i < size; i++)
{
Node *node = new Node(array[i]);
if (head == NULL)
{
head = node;
pHead = head;
}
else
{
pHead->next = node;
pHead = node;
}
}
return head;
}
void printLink(Node *link)
{
if (link == NULL)
return;
while (link != NULL)
{
cout << link->data << " ";
link = link->next;
}
cout << endl;
}
Node *partition(Node *&head1, Node *&head2)
{
if (head1 == NULL)
return NULL;
if (head1->next == NULL)
{
Node *pivot = head1;
head1 = NULL;
head2 = NULL;
return pivot;
}
Node *newHead1 = NULL;
Node *pNewHead1 = newHead1;
Node *newHead2 = NULL;
Node *pNewHead2 = newHead2;
Node *pivot = head1;
Node *pPivot = pivot;
head1 = head1->next;
while (head1 != NULL)
{
if (head1->data < pivot->data)
{
if (newHead1 == NULL)
{
newHead1 = head1;
pNewHead1 = newHead1;
}
else
{
pNewHead1->next = head1;
pNewHead1 = head1;
}
}
else if (head1->data == pivot->data)
{
pPivot->next = head1;
pPivot = head1;
}
else
{
if (newHead2 == NULL)
{
newHead2 = head1;
pNewHead2 = newHead2;
}
else
{
pNewHead2->next = head1;
pNewHead2 = head1;
}
}
head1 = head1->next;
}
if (newHead1 != NULL)
pNewHead1->next = NULL;
pPivot->next = NULL;
if (newHead2 != NULL)
pNewHead2->next = NULL;
head1 = newHead1;
head2 = newHead2;
return pivot;
}
Node *quickSort(Node *head)
{
if (head == NULL)
return head;
Node *head2 = NULL;
Node *pivot = partition(head, head2);
Node *newHead1 = quickSort(head);
Node *newHead2 = quickSort(head2);
Node *pNewHead1 = newHead1;
Node *pPivot = pivot;
if (newHead1 != NULL)
{
while (pNewHead1->next != NULL)
pNewHead1 = pNewHead1->next;
pNewHead1->next = pivot;
}
while (pPivot->next != NULL)
pPivot = pPivot->next;
pPivot->next = head2;
return newHead1 == NULL ? pivot : newHead1;
}
void main()
{
Node *head = construct();
printLink(head);
Node *newHead = quickSort(head);
cout << "after sort" << endl;
printLink(newHead);
}