问题描述:假设有N个人排成一圈,按顺序报数,报到M的人出局,此时,他两边的人重新形成圆圈。下一个人重新开始报数,报到M的人再出局,直到最后只剩下一人为止。求谁将是最后留下的人。
#include <stdio.h>
#include <stdlib.h>
typedef struct node* link;
struct node { int item; link next; };
int main(int argc, char *argv[])
{
int i, N = atoi(argv[1]), M = atoi(argv[2]);
link t = malloc(sizeof *t), x = t;
t->item = 1; t->next = t;
for (i = 2; i <= N; i++)
{
x = (x->next = malloc(sizeof *x));
x->item = i; x->next = t;
}
while (x != x->next)
{
for (i = 1; i < M; i++) x = x->next;
x->next = x->next->next; N--;
}
printf("%d\n", x->item);
return 0;
}
|
阅读(2171) | 评论(0) | 转发(0) |