#ifndef __JOSEPHUS_H__
#define __JOSEPHUS_H__
#include <stdio.h>
#include <stdlib.h>
#include <malloc.h>
typedef int QElemType;
typedef struct{
QElemType *base; //初始化动态分配储存空间
int front; //头指针,队列不空时指向队头
int rear; //尾指针,队列不空时指向队尾
}squeue;
void InitQueue(squeue *q);
int inqueue(squeue *q,int e,int max);
int dequeue(squeue *q,int max);
void DesQueue(squeue *q);
#endif
头文件
#include "josephus.h"
//初始化
void InitQueue(squeue *q){
q->base=(QElemType*)malloc(100*sizeof(QElemType));
if(!q->base)
exit(1);
q->front=q->rear=0;
}
//入队
int inqueue(squeue *q,int e,int max)
{
if((q->rear+1)%(max+1)==q->front)
return 1;
q->base[q->rear]=e; //数组分配空间里的第rear
q->rear=(q->rear+1)%(max+1);
return 0;
}
//出队
int dequeue(squeue *q,int max)
{
int e;
if(q->front==q->rear)
{
exit(1);
}
e=q->base[q->front];
q->base[q->front]=0;
q->front=(q->front+1)%max;
return e;
}
//清空
void DesQueue(squeue *q)
{ if(q->base)
free(q->base);
q->base=NULL;
q->front=q->rear=0;
}
函数体.c文件
#include "josephus.h"
void main()
{
int n,i,m,count,d,x;
squeue q;
printf("输入队列的长度n:");
scanf("%d",&n);
InitQueue(&q);
printf("请输入入队的值:\n");
for(i=1;i<=n;i++)
{
printf("输入队列的第%d个元素",i);
scanf("%d",&d);
inqueue(&q,d,n);
}
printf("输入第m个人出队:");
scanf("%d",&m);
count=n;
while(count!=1)
{
i=1;
while(i!=m)
{
q.front=(q.front+1)%n;
if(q.base[q.front]!=0)
{
i++;
}
}
x=dequeue(&q,n);
while(q.base[q.front]==0)
{
q.front=(q.front+1)%n;
}
printf("出%d\t",x);
count--;
}
x=dequeue(&q,n);
printf("出%d\t",x);
}
main函数