问题描述:有n个人围成一圈,顺序排号。从第一个人开始报数(从1到3报数),凡报到3的人 退出圈子,问最后留下的是原来第几号的那位。
约瑟夫环的解决方法很多,我这个只是针对题目没有打印模拟过程。当然如果不模拟过程的话用数学方法更容易得出结果。
#include<stdio.h>
#include<malloc.h>
struct people
{
int num;
struct people *next;
}*head,*p1,*p2;
people *creat(int n)
{
p1=(struct people*)malloc(sizeof(struct people));
head=p2=p1;
head->num=n;
while(--n)
{
p1=(struct people*)malloc(sizeof(struct people));
p2->next=p1;
p2->num=n+1;
p2=p1;
}
p1=p1->next=head;
return head;
}
int panduan(people *head)
{
int i=1;
while (p1!=p2)
{
while(i<3)
{
p2=p1;
p1=p1->next;
i++;
}
p2->next=p1->next;
p1=p2->next;
i=1;
}
return p1->num;
}
void main()
{
int n,b;
printf("请输入人数N!\n");
scanf("%d",&n);
head=creat(n);
b=panduan(head);
printf("剩余人数编号:%d\n",n-b+1);
}