约瑟夫环



#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;
 }


  



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值