2:有n个人围成一圈,顺序排号.从第一个人开始报数(从1到3报数),凡报到3的人退出圈子,
1个回答

扩展为:从1至N开始顺序循环数数,每数到M输出该数值,直至全部输出

链表实现:

#include

#include

typedef struct Node

{

int index;

struct Node *next;

}JosephuNode;

int Josephu(int n,int m)

{

int i,j;

JosephuNode *head,*tail;

head = tail = (JosephuNode *)malloc(sizeof(JosephuNode));

for (i = 1; i < n; ++i)

{

tail->index = i;

tail->next = (JosephuNode *)malloc(sizeof(JosephuNode));

tail = tail->next;

}

tail->index = i;

tail->next = head;

for (i = 1; tail != head; ++i)

{

for (j = 1; j < m; ++j)

{

tail = head;

head = head->next;

}

tail->next = head->next;

printf("第%4d个出局的人是:%4d号n",i,head->index);

free(head);

head = tail->next;

}

i = head->index;

free(head);

return i;

}

int main()

{

int n,m;

scanf("%d%d",&n,&m);

printf("最后胜利的是%d号!n",Josephu(n,m));

system("pause");

return 0;

}