单链表 快速排序

通过移动链表指针实现单链表快排:

#include <iostream>
using namespace std;

struct Node
{
	int data;
	Node* next;
};

Node* InitLinkList(int arr[],int N)  
{  
	if(N < 1)
		return NULL;  
	Node *p = new Node,*head = p;  
	p->data = arr[0];
	p->next = NULL;  
	for(int i=1; i<N; ++i)  
	{  
		p->next = new Node;
		p = p->next;  
		p->data = arr[i];
		p->next = NULL;  
	}  
	return head;  
}  

void print(Node* head)
{
	while (head)
	{
		cout<<head->data;
		head = head->next;
		if (head)
		{
			cout<<"->";
		}
	}
	cout<<endl;
}

Node* Partion(Node* front, Node* head, Node* tail)
{
	if (!head)
	{
		return NULL;
	}
	Node* tempHead = head;
	Node* prev = head;
	Node* cur = head->next;
	while (cur != tail)
	{
		if (cur->data < head->data)
		{
			Node* temp;
			prev->next = cur->next;
			cur->next = tempHead;
			tempHead = cur;
			cur = prev->next;
		}else
		{
			prev = prev->next;
			cur = cur->next;
		}
	}
	if (front)
	{
		front->next = tempHead;
	}
	return tempHead;
}

Node* QuickSort(Node* front, Node* head, Node* tail)
{
	if (!head || !head->next || head->next == tail || head == tail)
	{
		return head;
	}
	Node* tempHead = Partion(front, head, tail);
	Node* resultHead = QuickSort(front, tempHead, head);
	QuickSort(head, head->next, tail);

	return resultHead;
}

int main()
{	
	int Arra[13]={5,20,14,1, 8, 11, 2, 6, 9, 2, 4, 17, 13};  
	Node* head = InitLinkList(Arra, 13);

	print(head);
	head = QuickSort(NULL, head, NULL);
	print(head);

	return 0;
}


  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值