|
发表于 2017-5-11 09:41:56
|
显示全部楼层
每人持有密码的高级约瑟夫环代码用循环链表实现:
- #include<stdio.h>
- #include<stdlib.h>
- #define NUM 10
- #define START 2
- struct Date
- {
- int number;
- int password;
- struct Date *next;
- };
- void ListInsert(struct Date **pt,int num,int pass)
- {
- struct Date *tmp=NULL,*middle=NULL;
- tmp=(struct Date *)malloc(sizeof(struct Date));
- if(tmp==NULL) exit(1);
- tmp->number = num;
- tmp->password = pass;
- if((*pt)!=NULL)
- {
- middle = *pt;
- *pt = tmp;
- tmp->next = middle;
- }
- else
- {
- tmp->next=NULL;
- (*pt)=tmp;
- }
- // printf("插入成功!\n");
- }
- void ListPrint(struct Date *pt)
- {
- while(pt!=NULL)
- {
- printf("%d--%d\n",pt->number,pt->password);
- pt = pt->next;
- }
- putchar('\n');
- }
- void ListCircle(struct Date **pt)
- {
- struct Date *rear=*pt;
- while(rear->next!=NULL)
- rear=rear->next;
- rear->next=*pt;
- }
- void JosephusHard(struct Date *pt)
- {
- struct Date *kill,*previous;
- unsigned code=START;
- int i=0,FLAG=0;
- printf("kill game start!\n");
- printf("start code is: %d\n\n",START);
- while((pt->next)!=pt)
- {
- if(code<1)
- {
- printf("the code is error\n");
- exit(1);
- }
- else if(code==1)
- {
- FLAG=1;
- goto specialsec;
- }
- else if(code==2)
- {
- ;
- }
- else
- {
- for(i=code-2;i>0;--i)
- pt=pt->next;
- }
- kill=pt->next;
- code=kill->password;
- pt->next=kill->next;
- printf("kill No.%d\t",kill->number);
- printf("next code is %d\n\n",code);
- free(kill);
- pt=pt->next;
- specialsec:
- if(FLAG)
- {
- FLAG=0; //重置FLAG
- previous=pt;
- while(previous->next!=pt)
- {
- previous=previous->next;
- }
- kill=pt;
- pt=previous;
- code=kill->password;
- pt->next=kill->next;
- printf("kill No.%d\n",kill->number);
- printf("next code is %d\n",code);
- free(kill);
- pt=pt->next;
- }
-
- }
- printf("kill game over, No.%d survive!\n",pt->number);
- }
- int main()
- {
- struct Date *pt=NULL;
- for(int i=NUM ;i>0;i--)
- ListInsert(&pt,i, NUM+1-i);
- ListPrint(pt);
- ListCircle(&pt);
- JosephusHard(pt);
- return 0;
- }
复制代码 |
|