链队的基本操作实现及约瑟夫环问题的队列解法

代码:

#include <iostream>

using namespace std;

typedef char Item;
typedef struct QNode *pQNode;
typedef struct QNode
{
	Item data;
	QNode *link;	
}QNode;

typedef struct Queue
{
	pQNode front;
	pQNode rear;
}Queue,*LinkQueue;

void Copy(Item *dest,Item *src)
{
	*dest = *src;
}

void InitQueue(LinkQueue* Q);
void Enqueue(LinkQueue Q,Item item);
void Dequeue(LinkQueue Q,Item *item);
Item Front(LinkQueue Q);
bool Isempty(LinkQueue Q);
void Clear(LinkQueue *Q);
void PrintQueue(LinkQueue Q);

void InitQueue(LinkQueue* Q)
{
	*Q = new Queue;
	(*Q)->front = NULL;
	(*Q)->rear = NULL;
}
void Enqueue(LinkQueue Q,Item item)
{
	pQNode p = new QNode;
	Copy(&(p->data),&item);
	p->link = NULL;
	if(Q->rear == NULL)
	{
		Q->front = Q->rear = p;
	}
	else
	{
		Q->rear->link = p;
		Q->rear = p;
	}
}
void Dequeue(LinkQueue Q,Item *item)
{
	if(!Isempty(Q))
	{
		pQNode p = Q->front;
		Copy(item,&(p->data));
		if (Q->front == Q->rear)
			Q->front = Q->rear = NULL;
		else
			Q->front = Q->front->link;
		delete p;
	}
	
}
Item Front(LinkQueue Q)
{
	return Q->front->data;
}
bool Isempty(LinkQueue Q)
{
	return Q == NULL || Q->rear == NULL;
}
void Clear(LinkQueue *Q)
{
	pQNode  p = (*Q)->front;
	pQNode tmp; 
	while(p)
	{
		tmp = p->link;
		delete p;
		p = tmp;
	}
	delete (*Q);
	(*Q) = NULL;
}
void PrintQueue(LinkQueue Q)
{
	pQNode p = Q->front;
	cout<<"Queue currently Start:"<<endl;
	while(p)
	{
		cout<<"Qnode : "<<p->data<<endl;
		p = p->link;
	}
	cout<<"Queue End."<<endl;
}

int main()
{
	LinkQueue Q;
	InitQueue(&Q);
	for(int i=0;i<5;i++)
		Enqueue(Q,'A'+i);
	PrintQueue(Q);
	
	cout<<"Front node of current Queue : "<<Front(Q)<<endl;
	
	cout<<"QNode X Enqueue."<<endl;
	Enqueue(Q,'X');
	PrintQueue(Q);
	
	Item v;
	Dequeue(Q,&v);
	
	cout<<"QNode  :"<<v<<" Dequeued."<<endl;
	PrintQueue(Q);

	for(int i=0;i<5;i++)
		Dequeue(Q,&v);
	cout<<boolalpha<<Isempty(Q)<<endl;
	Clear(&Q);
	cout<<boolalpha<<Isempty(Q)<<endl;
	
	cout<<"Josephus M = 2,N = 7:"<<endl;
	InitQueue(&Q);
	for(int i=1;i<=7;i++)
		Enqueue(Q,'1'+i-1);
	int i = 1;
	while(!(Isempty(Q)))
	{
		if(i==2)
		{
			Dequeue(Q,&v);
			cout<<"Qnode : "<<v<<" dequeued."<<endl;
			i = 1;
		}
		if(Isempty(Q))
			break;
		Dequeue(Q,&v);
		Enqueue(Q,v);
		i++;		 
	}
	getchar();
} 
输出:

Queue currently Start:
Qnode : A
Qnode : B
Qnode : C
Qnode : D
Qnode : E
Queue End.
Front node of current Queue : A
QNode X Enqueue.
Queue currently Start:
Qnode : A
Qnode : B
Qnode : C
Qnode : D
Qnode : E
Qnode : X
Queue End.
QNode  :A Dequeued.
Queue currently Start:
Qnode : B
Qnode : C
Qnode : D
Qnode : E
Qnode : X
Queue End.
true
true
Josephus M = 2,N = 7:
Qnode : 2 dequeued.
Qnode : 4 dequeued.
Qnode : 6 dequeued.
Qnode : 1 dequeued.
Qnode : 5 dequeued.
Qnode : 3 dequeued.
Qnode : 7 dequeued.



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值