我的一次作业--Joseph环

来源:互联网 发布:男装网红淘宝店推荐 编辑:程序博客网 时间:2024/04/27 21:53

/*设计一个程序求出约瑟夫环的出列顺序。
约瑟夫问题的一种描述是:编号为1,2,…,n的n个人按顺时针方向围坐一圈,
每个人持有一个密码(正整数)。一开始任选一个正整数作为报数上限值m,
从第一个人开始按顺时针方向自1开始顺序报数,报到m时停止报数。报m的人
出列,将他的密码作为新的m 值,从他在顺时针方向上的下一个人开始重新
从1报数,如此下去,直到所有人全部出列为止。例如,n=7,7个人的密码依
次为:3,1,7,2,4,8,4,m的初值取6,则正确的出列顺序应为6,1,4,7,2,3,5。
要求使用单向循环链表模拟此出列过程。
*/
 #define NULL 0
#define LENGTH sizeof(struct Joseph)
#include "stdlib.h"
#include "stdio.h"

struct Joseph
{  int num;
   int secret;
   struct Joseph *next;
};/*定义结点num为序号,secret为密码*/

/*创建初始链表函数*/
struct Joseph *c() reat                       
{  struct Joseph *head;
   struct Joseph *p1,*p2;
   int n=0;
   p1=p2=(struct Joseph *)malloc(LENGTH);
   scanf("%d,%d",&p1->num,&p1->secret);
   head=NULL;

   while(p1->num!=0)
   {  n=n+1;
      if  (n==1) head=p1;
      else p2->next=p1;
      p2=p1;
      p1=(struct Joseph *)malloc(LENGTH);
      scanf("%d,%d",&p1->num,&p1->secret);
   }
   p2->next=head;
   return(head);
}

/*报数出列*/
void sort(struct Joseph * head,int m)

   struct Joseph *p1,*p2;
   int i;
   if (head==NULL)  printf("/n链表为空!/n");
   p1=head;
   while (p1->next!=p1)
   {
    for(i=1;i<m;i++)
    {  p2=p1;p1=p1->next;  }
       p2->next=p1->next;
       m=p1->secret;
       printf("%d  ",p1->num);
       p1=p2->next;
   }
   if (p1->next==p1)
   printf("%d ",p1->num);
   printf("/n");
}

void main()
{
 struct Joseph *head;
    int m;
    printf("/n输入数据:数据格式为序号,密码/n输入0,0为结束/n");
    head=creat();
    printf("输入 m值/n");
    scanf("%d",&m);
    if (m<1) printf("error! 请输入一个合法的 m值!");
    printf("出列的序号是:/n");
    sort(head,m);
}

原创粉丝点击