1. 程式人生 > >資料結構--迴圈佇列解決約瑟夫問題(純c)

資料結構--迴圈佇列解決約瑟夫問題(純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函式