【发布时间】:2013-06-01 17:28:29
【问题描述】:
我已经尝试了一段时间,但我无法弄清楚如何让下面的程序以 N 作为输入并生成一个 M,以便最后一个死去的士兵是 13th(N>13);
int main()
{
int N, M;
struct node { int player_id; struct node *next; };
struct node *p, *q;
int i, count;
printf("Enter N (number of players): "); scanf("%d", &N);
printf("Enter M (every M-th payer gets eliminated): "); scanf("%d", &M);
// Create circular linked list containing all the players:
p = q = malloc(sizeof(struct node));
p->player_id = 1;
for (i = 2; i <= N; ++i) {
p->next = malloc(sizeof(struct node));
p = p->next;
p->player_id = i;
}
p->next = q;//Close the circular linkedlist by having the last node point to the 1st
// Eliminate every M-th player as long as more than one player remains:
for (count = N; count > 1; --count) {
for (i = 0; i < M - 1; ++i)
p = p->next; p->next = p->next->next;
// Remove the eiminated player from the circular linked list.
} printf("Last player left standing is %d\n.", p->player_id);
return 0;
}
结果应该与this 相同(但我需要它在链表中,因为我不明白那个):>。
【问题讨论】:
-
如果有人想看问题,就在这里:bit.ly/JTeFaW
-
是的,伙计,这就是我用我的语言从一本书中翻译出来的问题,看起来像是抄袭了那本书
-
约瑟夫斯问题有一个封闭形式的解决方案。无需编写所有这些代码。
标签: c data-structures linked-list josephus