c++双向循环链表实现基数排序

c++双向循环链表实现基数排序

#include<iostream>
using namespace std;
#include<math.h>

typedef struct node
{
	int key;
	struct node *prior;
	struct node *next;
}LNode;

/*双循环链表是环形的,首尾相连的*/
//取下并删去双循环链表的第一个元素
template<class Type>
Type  *del_entry(Type *L)
{
	Type *p;
	p=L->next;
	if(p!=NULL){
		p->prior->next=p->next;
		p->next->prior=p->prior;
	}
	else 
		p=NULL;
	return p;
}

//把一个元素插入双循环链表的表尾
template<class Type>
void add_entry(Type *L,Type *p)
{
	p->prior=L->prior;
	p->next=L;
	L->prior->next=p;
	L->prior=p;
}

//取p所指向关键字的第i位数字(最低位为0位)
template <class Type>
int get_digital(Type *p,int i)
{
	int key;
	key=p->key;
	if(i!=0)
		key=key/pow(10,i);
	return key%10;
}

//把链表L1所有元素加到链表L的末端(删去L1的头结点)
template<class Type>
void append(Type *L,Type *L1)
{
	if(L1->next!=L1){
		L->prior->next=L1->next;    
		L1->next->prior=L->prior;  
		L1->prior->next=L;
		L->prior=L1->prior;
	}
}

//基数排序
template<class Type>
void radix_sort(Type *L,int k)
{
	Type *Lhead[10],*p;
	int i;
	for(i=0;i<10;i++){
		Lhead[i]=new Type;//分配10个链表的头结点
	}
	for(i=0;i<k;i++){
		for(int j=0;j<10;j++){    //把10个链表置为空表
			Lhead[j]->prior=Lhead[j]->next=Lhead[j];
		}
		while(L->next!=L){
			p=del_entry(L);    //删去L的第一个元素,使P指向该元素
			j=get_digital(p,i);    //从P所指向的元素关键字取第i个数字
			add_entry(Lhead[j],p);  //把p所指向的元素加入链表Lhead[j]的表尾
		}
		for(j=0;j<10;j++){
			append(L,Lhead[j]);   //把10个链表的元素链接到L
		}
	}
	for(i=0;i<10;i++)
		delete(Lhead[i]);   //释放10个链表元素的头结点
}

void main()
{
	LNode *L=new LNode();
	LNode *p;
	L->next=L;
	L->prior=L;
	cout<<"请输入初始链表的值:"<<endl;
	for(int i=0;i<8;i++){
		p=new LNode;
		cin>>p->key;
		add_entry(L,p);
	}
	radix_sort(L,8);
	p=L->next;
	cout<<"基数排序后:"<<endl;
	while(p!=L){
		cout<<p->key<<" ";
		p=p->next;
	}
	cout<<endl;
}

运行结果如下:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值