這是用堆棧的隊列做的約瑟夫環,如果大家有什麼覺得我寫的難以理解可以留言告訴我。
#include<stdio.h>
#include<malloc.h>
typedef int Position;
typedef struct QNode *PtrToQNode;
struct QNode
{
int *date;
Position Rear;
int MaxSize;
};
typedef PtrToQNode Queue;
Queue CreateQueue(int MaxSize);
bool AddQ(Queue Q, int date);
void deal(Queue Q, int n, int date);
int main()
{
int i, date, n, MaxSize;
struct QNode *t;
printf("請輸入約瑟夫環的長度:");
scanf("%d", &MaxSize);
printf("請輸入約瑟夫環的輸出位序:");
scanf("%d", &n);
MaxSize = MaxSize+1;
t = CreateQueue(MaxSize);
AddQ(t, MaxSize);
deal(t, n, MaxSize);
return 0;
}
Queue CreateQueue(int MaxSize)
{
Queue Q = (Queue) malloc(sizeof(struct QNode));
Q->date = (int *)malloc(sizeof(int));
Q->Rear = 0;
Q->MaxSize = MaxSize;
return Q;
}
bool AddQ(Queue Q, int MaxSize)
{
Position i;
for( i=1; i<=MaxSize;i++)
{
Q->Rear=(Q->Rear+1)%Q->MaxSize;
Q->date[Q->Rear] = i;
}
Q->date[MaxSize] = NULL;
}
void deal(Queue Q, int n, int MaxSize)
{
Position i=1, sum=0, k=1, L, u;
L = MaxSize-1;
u = MaxSize-1;
while(u)
{
for( i=1; i<=MaxSize; i++ )
{
if( Q->date[i]!=0 )//在這裏判斷 數值是否爲0,否則計算輪到的次數
sum++;
else
continue;
if( sum%n==0 )
{
printf("第%d個輸出的是:%d\n", k, Q->date[i]);
k++;
Q->date[i] = 0;
u--; //當輸出的次數等於MaxSize就退出
}
if( i==L )//每次當i等於 MaxSize就讓i重1開始重新算起
break;
}
}
}
編譯器:DEV C++