约瑟夫环问题

本文介绍了一个简单的约瑟夫环游戏实现方案,通过C语言编程实现了一个循环链表来模拟儿童报数出圈的游戏过程,并展示了完整的源代码。
#include <stdio.h>
#include <stdlib.h>

typedef struct cerclelink
{
    int num;
    struct cerclelink *next;
}Node,*pNode;

pNode create(int );
int Joseph(pNode,int);

int main()
{
    int n,k;
    printf("enter number of children:  ");
    scanf("%d",&n);
    printf("enter the number which use to circle :");
    scanf("%d",&k);
    pNode head=create(n);
    printf("\nthe quence of out of list is :\n");
    /*调用约瑟夫游戏函数进行计算,之所以要k-1是因为指针/
       要放在将要删除的那个元素的前一个元素上面*/
    printf("the last children is :%d\n",Joseph(head,k-1));
    return 0;
}

pNode create(int n)
{
    pNode head,p,q;
    head=(pNode)malloc(sizeof(Node));/*为头节点分配内存*/
    head->num=1;/*先为头节点赋值1*/
    p=head;
    int i;
    for(i=2;i<=n;i++)
    {
        q=(pNode)malloc(sizeof(Node));
        q->num=i;
        p->next=q;
        p=q;
        p->next=head;/*每次都将最后一个节点指向头节点*/
    }
    return head;
}

int Joseph(pNode head ,int k)
{
    int count=1;
    pNode p=head,q=head,t=NULL;
    if(k==0)/*如果每次都只查到1,那就相当于顺序出列了*/
    {
        while(p->next!=head)
            p=p->next;
        return p->num;
    }
    else
    {
        while(p->next!=p)
        {
            while(count!=k)
            {
                p=q=q->next;
                count++;
            }
            count=1;
            q=q->next->next;
            t=p->next;
            p->next=q;
            p=q;
            printf("\n***%d***\n",t->num);
            free(t);
        }
        return p->num;
    }

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值