我已经尝试了一段时间,但我不知道如何让下面的程序以 N 作为输入并生成一个 M,以便最后一个死去的士兵是第 13 个(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;
}
结果应该与这个相同(但我需要它在链表中,因为我不明白那个):>。