C语言数据结构之利用循环链表解决约瑟夫问题

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/a1135004584/article/details/79328172

约瑟夫问题:

  • 据说著名犹太历史学家 Josephus有过以下的故事:在罗马人占领乔塔帕特后,39 个犹太人与Josephus及他的朋友躲到一个洞中,39个犹太人决定宁愿死也不要被敌人抓到,于是决定了一个自杀方式,41个人排成一个圆圈,由第1个人开始报数,每报数到第3人该人就必须自杀,然后再由下一个重新报数,直到所有人都自杀身亡为止。然而Josephus 和他的朋友并不想遵从。首先从一个人开始,越过k-2个人(因为第一个人已经被越过),并杀掉第k个人。接着,再越过k-1个人,并杀掉第k个人。这个过程沿着圆圈一直进行,直到最终只剩下一个人留下,这个人就可以继续活着。问题是,给定了和,一开始要站在什么地方才能避免被处决?Josephus要他的朋友先假装遵从,他将朋友与自己安排在第16个与第31个位置,于是逃过了这场死亡游戏。


这个题目有很多种解法,但是目前这里用循环链表实现


实现代码:

#include <stdio.h>
#include <malloc.h>

/**
 * 循环链表
 */
typedef struct cirNode{
    int id;//标号
    struct cirNode * next;
} * CirLinkList;


//尾插法添加元素
void addNode(CirLinkList cirLinkList,int id)
;

int main(void)
{
    CirLinkList cirLinkList = (struct cirNode *)malloc(sizeof(struct cirNode));
    int i,k=41,m=3;

    for(i=1;i<=k;i++)
    {
        addNode(cirLinkList,i);
    }//添加41个犹太人id

    struct cirNode *cn,*temp;
    cn = cirLinkList->next;
    while(cn->next)
        cn = cn->next;

    cn->next = cirLinkList->next;//尾部链接到头部使之形成闭合的环路
    //cn当前在导数第一个
    free(cirLinkList);//把头部指针的空间给释放掉
    m%=k;

    while(cn != cn->next)//当循环链表为空时停止循环
    {
        for(i=1;i<m;i++)//移动m-1            cn=cn->next;

        temp = cn->next;
        cn->next = cn->next->next;
        printf("%d->",temp->id);
        free(temp);
    }

    printf("%d\n",cn->id);
    free(cn);
    return 0;
}

//尾插法添加元素
void addNode(CirLinkList cirLinkList,int id)
{
    struct cirNode * cn;

    if(!cirLinkList->next)
    {
        cirLinkList->next = (struct cirNode *)malloc(sizeof(struct cirNode));
        cirLinkList->next->id = id;
    }else{
        cn = cirLinkList->next;
        while(cn->next)
            cn = cn->next;

        cn->next = (struct cirNode *)malloc(sizeof(struct cirNode));
        cn->next->id = id;
    }
}

结果:

3->6->9->12->15->18->21->24->27->30->33->36->39->1->5->10->14->19->23->28->32->37->41->7->13->20->26->34->40->8->17->29->38->11->25->2->22->4->35->16->31

可见16和31是最后两个

猜你喜欢

转载自blog.csdn.net/a1135004584/article/details/79328172