约瑟夫环(队列*堆栈)

这是用堆栈的队列做的约瑟夫环,如果大家有什么觉得我写的难以理解可以留言告诉我。

#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++


阅读更多 登录后自动展开
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页