//约瑟夫环问题,其实就是循环链表,考察节点的删除操作
#include <stdio.h>
#include <stdlib.h>
int n;
struct node
{
int num;
struct node * next;
};
void init(node ** p)//必须要双星,node*表类型(即和传过来的a类型一样),*p用来接收地址
{
*p = (node *)malloc(sizeof(node));
node * b = *p;
if((*p) == NULL)
exit(0);
(*p)->num = 1;
for(int i = 2; i <= n; i++)
{
(*p)->next = (node *)malloc(sizeof(node));
*p = (*p)->next;
(*p)->num = i;
if(i == n)
(*p)->next = b;
}
}
bool del(node * c, int mm)
{
node * tmp = c->next;
c->next = c->next->next;
free(tmp);
while(c->next != c)
{
for(int i = 1; i < mm; i++)
c = c->next;
tmp = c->next;
c->next = c->next->next;
free(tmp);
}
if(c->num == 2)
return true;
return false;
}
int main(void)
{
int m;
while(scanf("%d", &n), n)
{
node * a = NULL;
for(m = 2; ; m++)
{
init(&a);//一定要有取值符,否则a的地址改变不了
if(del(a, m))
break;
}
printf("%d\n", m);
}
//system("pause");
}
06-15
829
