代码:
#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.