约瑟夫问题的提法:
n个人围成一个圆圈,首先第1个人从1开始一个人一个人顺时针报数, 报到第m个人,令其出列。然后再从下一个人开始,从1顺时针报数,报到第m个人,再令其出列,…,如此下去, 直到圆圈中只剩一个人为止。此人即为优胜者。
#include <stdio.h>
#include <malloc.h>
struct node{
int data;
struct node *next;
};
int main()
{
int numOfPeople; // 参加游戏的人数
int countsFirst; // 第一个开始报数的人
int key; // 报数的关键数字
int i; // 计数变量
struct node *p, *tmp, *head;
printf("Please enter the number of people: ");
scanf(" %d", &numOfPeople);
printf("Please enter the number of the person who counts first: ");
scanf(" %d", &countsFirst);
printf("Please enter the key number: ");
scanf(" %d", &key);
head = (struct node*)malloc(sizeof(struct node));
p = head;
for (i = 1; i < numOfPeople; i++)
{
// 定义所有人的编号
p->data = i;
p->next = (struct node*)malloc(sizeof(struct node));
p = p->next;
}
// 连接成环
p->data = numOfPeople;
p->next = head;
p = head;
while (p->data != p->next->data) // 剩下的最后一位是自己首尾相连的
{
while(p->data != countsFirst)
p = p->next;
if (1 == key) // 关键数字是1的情况
{
for(i = 1; i < numOfPeople; i++)
{
printf("%d out!\n", p->data);
p = p->next;
}
printf("%d win! ", p->data); // 最后一位胜利
return 0;
}
else
{
for (i = 1; i < key - 1; i++)
p = p->next;
}
tmp = p->next;
printf("%d out!\n", tmp->data);
countsFirst = tmp->next->data;
p->next = tmp->next;
}
printf("%d win! ", p->data);
return 0;
}