单链表实现约瑟夫环
#include <stdio.h>#include <stdlib.h>
#include <conio.h>
typedef struct stu
{
int num;
int move;
int pwd;
struct stu *next;
}Node,*Linklist;
void kong(Linklist &L)
{
L=(Linklist)malloc(sizeof(Node));
L->next=NULL;
}
void creat(Linklist &L,int n)
{
int i;
Linklist r,s;
r=L;
for(i=1;i<=n;i++)
{
s=(Linklist)malloc(sizeof(Node));
s->num=i;
s->move=i;
printf("请输入第%d个人的密码:",i);
scanf("%d",&s->pwd);
r->next=s;
r=s;
}
r->next=NULL;
}
void huan(Linklist &L,int n,int m)
{
int out,x,f,j;
f=x=1;
Linklist p,h,g,p1,g1;
p1=L;
p=L->next;
g=L->next;
while(p)
{
out=m%n;
if(out==0) out=n;
if(p->move==out)
{
printf("\n%d",p->num);
m=p->pwd;
n--;
h=p;
p=p->next;
free(h);
if(out==1)
{
L->next=p;
}
else
{
for(;x<f;x++)
p1=p1->next;
if(p==NULL)
{
p=L->next;
p1->next=NULL;
}
else
{
p1->next=NULL;
L->next=p;
g1=p;
while(p->next)
p=p->next;
p->next=g;
g=g1;
}
}
p=L->next;
for(j=1;j<=n;j++)
{
p->move=j;
p=p->next;
}
p=L->next;
g=L->next;
x=f=1;
p1=L;
}
else
{
p=p->next;
f++;
}
}
}
void main()
{
Linklist L;
int m,n;
printf("上限m=");
scanf("%d",&m);
printf("人数n=");
scanf("%d",&n);
kong(L);
creat(L,n);
huan(L,n,m);
getch();
free(L);
}