#include<stdio.h>
#include<stdlib.h>
#define MAX 100
typedef struct nodetype
{
int id;
int password;
struct nodetype *next;
}nodetype;
void creatlist(nodetype **,int);
nodetype *getnode(int,int);
int printlist(nodetype *);
int josephusoperate(nodetype **,int);
void creatlist(nodetype **pphead,int n)//**的意思是?
{
int i=0;
int ipassword=0;
nodetype *pnew=NULL;
nodetype *pcur=NULL;
for(i=1;i<=n;i++)
{
printf("请输入第%d个人的密码: \n",i);
scanf("%d",&ipassword);
pnew=getnode(i,ipassword);
if(*pphead==NULL)
{
*pphead=pcur=pnew;
pcur->next=*pphead;
}
else
{
pnew->next=pcur->next;
pcur->next=pnew;
pcur=pnew;
}
}
printf("完成单项循环链表的建立\n");
}
nodetype *getnode(int i,int ipassword)
{
nodetype *pnew=NULL;
pnew=(nodetype *)malloc(sizeof(nodetype));
if(!pnew)//有疑问
{
printf("error,the memory is not enough\n");
exit(-1);
}
pnew->id=i;
pnew->password=ipassword;
pnew->next=NULL;
return pnew;
}
int printlist(nodetype *phead)
{
nodetype *pcur;
pcur=phead;
if(phead==NULL)
{
printf("the list is empty\n");
return 0;
}
else
{
printf("**id*****password**\n");
do
{
printf("%d %d\n",pcur->id,pcur->password);
pcur=pcur->next;
}while(pcur!=phead);
return 1;
}
}
int josephusoperate(nodetype **pphead,int ipassword)
{
int count=0;
int flag=1;
nodetype *pprv=NULL;
nodetype *pcur=NULL;
nodetype *pdel=NULL;
pprv=pcur=*pphead;
while(pprv->next!=*pphead)
pprv=pprv->next;
while(flag)
{
for(count=0;count<ipassword;count++)
{
pprv=pcur;
pcur=pcur->next;
}
if(pprv==pcur)
flag=0;
pdel=pcur;
pprv->next=pcur->next;
pcur=pcur->next;
ipassword=pdel->password;
printf("第%d个人出列,密码:%d\n",pdel->id,pdel->password);
free(pdel);
}
*pphead=NULL;
getchar();
return 0;
}
int main(void)
{
int n=0;
int m=0;
int k=0;
nodetype *phead=NULL;
do
{
if(n>MAX)
printf("人数过多,请重新输入\n");
printf("请输入人数\n");
scanf("%d",&n);
}while(n>MAX);
printf("请输入初始密码\n");
scanf("%d",&m);
creatlist(&phead,n);
printf("打印循环链表\n");
k=printlist(phead);
printf("打印出队情况\n");
k=josephusoperate(&phead,m);
return 0;
}