数据结构--循环队列解决约瑟夫问题(纯c)

#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函数

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值