正文

约瑟夫环程序2005-05-03 22:47:00

【评论】 【打印】 【字体: 】 本文链接:http://blog.pfan.cn/super/847.html

分享到:

此程序用链表实现,比较简单.

#include
#include
#include
#define overflow -2
#define ture 1
#define False 0
typedef struct circle{
    int number;
    int password;
    struct circle *next;
}circle,*linkcircle;
void initcircle(linkcircle &l,int n)   /*初始化循环单链表*/
{  int i;  linkcircle p,newbase;
   newbase=(linkcircle)malloc(sizeof(circle));
   if(!newbase)  exit(overflow);
   p=l=newbase;
   printf("Input %d passwords:\n",n);
   for(i=1;i    {  scanf("%d",&p->password);
      if(p->password<1){
          printf("One password is error.\n");
          exit(0);
      }
      p->number=i;
      newbase=(linkcircle)malloc(sizeof(circle));
      if(!newbase)  exit(overflow);
      p->next=newbase;
      p=p->next;
  }
  scanf("%d",&p->password);
  p->number=i;
  p->next=l;
}
void sortcircle(linkcircle &l,int m)  /*排列函数*/
{  int i,change=ture;
   linkcircle p,q;
   p=l;
   printf("The result: ");
   m=m-1;
   while(change)  /* change为空表标志*/
   {  i=1;
      while(i       {  p=p->next;
         i++;
      }
      q=p->next;
      p->next=q->next;
      m=q->password;
      printf("%d ",q->number);
      if(q->next==q)
          change=False;
      free(q);
   }
   putchar('\n');
}
void main()
{  int n,m;
   linkcircle l;
   printf("Input the number of persons.\nn=");
   do{scanf("%d",&n);
      if(!n)  printf("Input error!\n");
      }while(!n);
   initcircle(l,n);
   printf("Input the limit.\nm=");
   scanf("%d",&m);
   sortcircle(l,m);
   getch();
}


阅读(7744) | 评论(2)


版权声明:编程爱好者网站为此博客服务提供商,如本文牵涉到版权问题,编程爱好者网站不承担相关责任,如有版权问题请直接与本文作者联系解决。谢谢!

评论

loading...
您需要登录后才能评论,请 登录 或者 注册