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;
}
本文介绍了一个典型的约瑟夫环问题的C语言实现过程,通过定义节点结构体和使用链表来模拟报数淘汰的过程,并最终找出获胜者。代码详细展示了如何创建环形链表并进行每轮报数直至最后一个节点。
945

被折叠的 条评论
为什么被折叠?



