约瑟夫环

来源:互联网 发布:郑州百知 编辑:程序博客网 时间:2024/04/25 02:32
#include "stdio.h"
#include "stdlib.h"
#include "malloc.h"


struct person
{
    short num;
    short password;
    struct person *next; 
};


struct person *create_list(int N);
void output(struct person *head);
 
void main()
{
 struct node *head,*p,*q;
 int c=0,k,N,high;
 printf("How many people to play the game/n");
 scanf("%d",&N);
 head=create_list(N);
 output(head);
 
 p=head;
 c=1;
 printf("/n Please input a heigh number(必须大于1,否则会出错):  ");
 scanf("%d",&high);
 printf("/n The output sequence:/n");
 k=N;
 while(k>0)/*出列一人,K减1, 直到所有人全都出来*/
 {
  if(c==high-1)
  {   
   q=p->next;   
   p->next=q->next;
   
   printf(" the %d man is out /n",q->num);
   high=q->password;/*将q (出列的人) 的密码作为新的high(上限值)*/
   free(q);/*释放内存*/
   c=0;
   k--;
  }
  else
  {
   c++;
   p=p->next;
  }
 }
    return;
}

 
struct person *create_list(int N)
{
 struct person *head,*p,*temp;
 int i,password;
 head=(struct person *) malloc(sizeof(struct person));/*申请新节点 并分配内存空间*/
 if(!head)
 {
  printf("/nMemory allocation error!/n");
  exit(1);
 }
 printf("/nPlease input the First man's password (sure be >=1):");
 scanf("%d",&password);
 head->password=password;
 head->num=1;
 head->next=head;
 
 
 for(i=2;i<=N;i++)
 {
  p=(struct person *) malloc(sizeof(struct person));/*申请新节点 并分配内存空间*/
  printf("/nPlease input the %d man's password (sure be >=1):",N-i+2);/*使用头插法添加人员,  第二个插入的人排在最后*/
  scanf("%d",&password);
  p->password=password;
  p->num=N-i+2;/*头插法*/
  p->next=head->next;
  head->next=p;    
 }
 return head;

 /*********************************************************/
 void output(struct person *head)
 {
  struct person *p;
  p=head;
  do
  {
   printf("/nthe %d man's password is:%d",p->num,p->password);
   p=p->next;
  }while(p!=head);
 }
 

 
原创粉丝点击