Josephus有过的故事:39 个犹太人与Josephus及他的朋友躲到一个洞中,39个犹太人决定宁愿死也不要被敌人抓。于是决定了自杀方式,41个人排成一个圆圈,由第1个人开始报数,每报数到第3人该人就必须自杀。然后下一个重新报数,直到所有人都自杀身亡为止。然而Josephus 和他的朋友并不想遵从,Josephus要他的朋友先假装遵从,他将朋友与自己安排在第16个与第31个位置,于是逃过了这场死亡游戏。
代码:
#include <stdio.h>
#include <stdlib.h>
#include <malloc.h>
#define DataType int
typedef struct node{
DataType data;
struct node *next;
}nodes;
//创建循环链表。
nodes *createList(int n){
nodes *head;
nodes *temp;
nodes *news;
DataType data,i=1;
head=(nodes *)malloc(sizeof(nodes));
head->next=NULL;
temp=head;
while(i<=n){
news=(nodes *)malloc(sizeof(nodes));
temp->next=news;
//scanf("%d",&data);
news->data=i++;
temp=news;
}
temp->next=head->next;
free(head);
//测试是否创建成功
/*nodes *node=temp->next;
while(n){
printf("%d ",node->data);
node=node->next;
n--;
}*/
return temp;
}
void Josephus(nodes *tail,int m){
nodes *temp;
int i=0;
while(tail->next!=tail){//循环链表的最后还剩一个,且自己指向自己。
for(i=0;i<m;i++){ //每一次数到m,那么杀一个。
temp=tail;
tail=tail->next;
}
printf("%d ",tail->data);
temp->next=tail->next;
}
printf("\n胜者:%d",tail->data);
}
int main(int argc, char *argv[]) {
nodes *temp=createList(41);
Josephus(temp,3);
return 0;
}
结果截图: