您的位置:首页 > 其它

啰嗦的约瑟夫问题

2016-01-03 17:24 204 查看
#include<stdio.h>

#include<malloc.h>

#define Len sizeof(struct node)

struct node

{

    int num;

    struct node*next;

};

struct node* create(int m) //建立循环链表

{

    struct node*head,*p1,*p2;

    int i;

    for(i=1;i<=m;i++)

    {

        if(i==1)

        {

            head=p2=(struct node*)malloc(Len);

            p2->num=1;

        }

        else

        {

            p1=(struct node*)malloc(Len);

            p1->num=i;

            p2->next=p1;

            p2=p1;

        }

    }

    p1->next=head;

    return head;

}

void print(struct node*head) // 打印循环链表

{

    struct node*p=head;

    do

    {

        printf("%4d",p->num);

        p=p->next;

    }

    while(p!=head);

}

struct node* kill(int n,struct node*p1) //一次杀一个,要求输入n和起始地址

{

    int i;

    struct node*p2;

    for(i=1;i<=n;i++)

    {

        if(i==n)

        {

            p2->next=p1->next;

            return(p1->next);

        }

        else

        {

            p2=p1;

            p1=p1->next;

        }

    }

}

int flag(int n,struct node*survivor) //确认幸存者的人数够不够一次循环

{

    struct node*p1;

    int i;

    p1=survivor;

    for(i=1;i<=n;i++)

    {

        p1=p1->next;

    }

    if(p1==survivor)return 1;

    else return 0;

}

void main()

{

    int m,n,f=0;

    struct node*head,*survivor;

    scanf("%d,%d",&m,&n);

    head=create(m);

    /*print(head);

    printf("\n");*/

    survivor=head;

    while(f==0)

    {

        f=flag(n,survivor);

        survivor=kill(n,survivor);

        //print(survivor);

        //printf("\n");

    }

        print(survivor);

        printf("\n");

}


内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: