约塞夫环
关键:在于每次选人的时候都是把出队和进队结合起来
//************************************************约塞夫环****************************************************
#include <iostream>
using namespace std;
const int maxSize = 100;
struct QNode {
int Data[maxSize];
int rear, front;
int length; //定义长度方便后面跳出循环
};
typedef QNode* Queue;
void Init(Queue &q)
{
q = new QNode;
q->front = q->rear = 0;
q->length = 0;
}
bool EnQueue(Queue& q, int e)
{
if ((q->rear + 1) % maxSize == q->front)
return false;
q->Data[q->rear] = e;
q->rear = (q->rear + 1) % maxSize;
q->length++;
return true;
}
bool DeQueue(Queue& q, int& e)
{
if (q->front == q->rear)
return false;
e = q->Data[q->front];
q->front = (q->front + 1) % maxSize;
q->length--;
return true;
}
void YSF(int size,int time)
{
Queue q;
Init(q);
int e;
for (int i = 1; i <= size; i++) //为队列内部赋值
{
EnQueue(q,i);
}
while (q->length != 0) //设置跳出循环的条件为q的长度不为0
{
for (int i = 1; i <= time; i++)
{
DeQueue(q, e); //出队列,若没有到达次数,则通过进队,再次循环。若达到次数,则直接出队列,并打印出来
if (i != time)
EnQueue(q, e);
else
cout << e << " ";
}
}
}
int main()
{
int size,time;
cout << "请输入要约塞夫环的总数和每次出列的次数:";
cin >> size>>time;
cout << "出列顺序为:";
YSF(size, time);
}