生死游戏算法

#include <stdio.h>
#include <malloc.h>
/* http://home.ustc.edu.cn/~jeyo        QQ:59521550            风过无痕 */
typedef struct game
{
     int member;
     struct game *next;
}GNode;
void main()
{
     struct game *CreateGame(GNode *head,int m);    
     void GameOut(GNode *head,int m,int n);
     GNode *head=NULL;
     int m,n;
     printf("Please input the number to the people: ");
     scanf("%d",&m);
     printf("Please input the other number to the count: ");
     scanf("%d",&n);
     while(n>m)
     {    
            printf("Enter error ! the number of people's is must be larger then the number of count's! Please retry Enter: ");
            printf("Please input the number to people: ");
            scanf("%d",&m);
            printf("Please input the other number to count: ");
            scanf("%d",&n);
            head=CreateGame(head,m);
            GameOut(head,m,n);
        }
}
struct game *CreateGame(GNode *head,int m)
{
     GNode *p=NULL,*q=NULL;
     int count=0;
     while(m>count)
         if(!head)
         {
                head=(struct game *)malloc(sizeof(GNode));
head->member=++count;
                p=q=head;
         }
         else
         {
                p=(struct game *)malloc(sizeof(GNode));
p->member=++count;
                q->next=p;
                q=p;
         }
         p->next=head;
         return head;
}
void GameOut(GNode *head,int m,int n)
{
     GNode *p=NULL,*q=NULL;
     int count=1;
     q=p=head;
     while(m>=n)
     {
            p=p->next;
            count++;
            if(count==n)
            {
                 printf("%3d",p->member);
                 q->next=p->next;
                 p=p->next;
                 q=p;
                 count=1;                    
                 m--;
             }
             else
                 q=p;
        }
}
 
以上代码是我亲编写的约瑟夫生死游戏算法,用于实现输出被扔出圈子的人的编号.已测试过多次,如果要求输出最后一个出圈的人的编号的话,需对程序的GameOut函数稍作改动.其它部分都不变.

你可能感兴趣的:(游戏,算法,职场,休闲,生死)