C语言算法实现约瑟夫环3
#include"stdio.h"
#include"stdlib.h"
typedef struct lnode //定义结构体
{
int num,code; //编号和密码
struct lnode *next;
}lnode;
int main()
{
int i,j,key,n;
lnode *p,*s,*head;//结构体指针
head=(lnode *)malloc(sizeof(lnode)); //为头结点分配空间
p=head;
printf("please input the whole number of people: ");
scanf("%d",&n);
for(i=1;i<=n;i++) //循环
{
printf("%d",i); //输出n个人的编号
printf("Password: ");
scanf("%d",&key); //n个人的密码
s=p;
p=(lnode *)malloc(sizeof(lnode)); //创建新的结点
s->next=p;
p->num=i;
p->code=key;
}
p->next=head->next;
p=head;
head=head->next; //将p移到头结点
free(p);
printf("\n Iput m:");
scanf("%d",&key);
do
{
j=1; //j记数
p=head;
while(j<key) //将j的值加到与m相等为止
{
s=p;
p=p->next;
j++;
}
i=p->num;//将p指向的编号赋给i
key=p->code; //将p指向的密码赋给key
printf("Out:");
printf("Number%d\n",i);
s->next=p->next;
head=p->next; //重新定义head,下次循环的开始结点
free(p);
n--; //每循环一次人是减1
}while(n>0);
}