⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 f22.c

📁 约瑟夫环
💻 C
字号:
    #include<stdio.h>
    #include<stdlib.h>

  struct Lnode    /*循环链表的存储结构*/

{

    int number;

    int password;

    struct Lnode *next;

}* p,*q,*head;

struct Lnode *creat(int n) /*创建循环链表,参数代表结点个数*/
 {

       int i;
       int m;
       head=p=(struct Lnode*)malloc(sizeof(struct Lnode));  /*建立第一个节点*/
       if(p==0) return(0);  /*存储分配失败*/


    for(i=1;i<=n;i++)

       {

        printf("please enter the %d people's password:",i); /*取得每个人的密码*/
        scanf("%d",&(p->password));

          if((p->password)<=0)   /*输入的密码不合法*/
          {
           printf("password is irregular\n") ;
           return 0;
           }

          p->number=i;
          if(i<n)  /*不是最后一个节点*/
          {
          q=(struct Lnode*)malloc(sizeof(struct Lnode));  /*q指向新建节点*/
          if(q==0) return(NULL);  /*存储分配失败*/
          p->next=q;   /*在第一个节点之后加入*/
          p=q;
          }

        }

        p->next=head;  /*链表构造完成后使最后一个节点指向第一节点构成循环链表*/
       
        return(head); /*返回链表的首地址*/
   }


    int main(void)

{
      

       int n;

       int i;

       int m;

     printf("please enter the number of people n:");  /*获得最初围坐的人数*/

    scanf("%d",&n);
     if(n<=0)     /*输入的n不合法*/
     {
     printf("n is irregular\n") ;
     return 0;
     }
    printf("please enter the number m:");   /*获得开始的报数上限值*/
    scanf("%d",&m);
    if(m<=0)    /*输入的m不合法*/
     {
     printf("n is irregular\n") ;
     return 0;
     }

    q=creat(n); /*调用创建链表函数,取得链表首地址*/
     if(p==0)  {return (0);}/*创建链表失败*/
  
	 printf("chu lie shun xu:\n") ;  /*输出提示*/

	 
	 /*输出结果部分*/
  while(n)   /*链表不空*/
    {
   for(;m>1;--m)     /*找到要出列的人*/
    {
      q=q->next;
      p=p->next;
     }
   
   m=q->password;
   printf("%d ",q->number);  /*输出出列人的号码*/
   p->next=q->next;
   free(q);  /*删除出列节点*/
   q=p->next;
   n--;
 
}
    getch();


    return 0;

}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -