基于链表的快速排序

写了大半天,终于折腾出了这个难看的链表快速排序:

#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);
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值