Linked list OJ - Joseph problem of circular linked list

Tip: After the article is written, the table of contents can be automatically generated. For how to generate it, please refer to the help document on the right.


Preface

世上有两种耀眼的光芒,一种是正在升起的太阳,一种是正在努力学习编程的你!一个爱学编程的人。各位看官,我衷心的希望这篇博客能对你们有所帮助,同时也希望各位看官能对我的文章给与点评,希望我们能够携手共同促进进步,在编程的道路上越走越远!


提示:以下是本篇文章正文内容,下面案例可供参考

1. Joseph’s problem of circular linked list:

The famous Josephus problem

It is said that the famous Jewish Josephus had the following story: After the Romans occupied Chotapat, 39 Jews hid in a cave with Josephus and his friends. The 39 Jews decided that they would rather die than be caught, so they decided A method of suicide was developed. 41 people lined up in a circle, and the first person counted. Every time the third person was counted, the person must commit suicide, and then the next person counted again until everyone committed suicide.

However, Josephus and his friends did not want to comply. Josephus asked his friends to pretend to comply first. He placed his friends and himself in the 16th and 31st positions, thus escaping the death game.

Code demo:

/**
 * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
 *
 * 
 * @param n int整型 
 * @param m int整型 
 * @return int整型
 */
 typedef struct ListNode ListNode;
 //申请一个新的节点
 ListNode*ListBuyNode(int x)
 {
    ListNode*node = (ListNode*)malloc(sizeof(ListNode));
    if(node == NULL)
    {
        perror("malloc fail!");
        exit(1);
    }
    node->val = x;
    node->next = NULL;
    return node;
 }
 //创建带环链表
 ListNode*Greatelist(int n)
 {
    //创建链表
    ListNode*phead = ListBuyNode(1);
    ListNode*pTail = phead;
    for(int i=2;i<=n;i++)
    {
        ListNode*node = ListBuyNode(i);
        pTail->next = node;
        pTail = pTail->next;
    }
    //以上只是在创建单链表
    pTail->next = phead;
    return pTail;//有尾节点就能找到头节点,返回头节点的话还要遍历链表才能找到尾节点
 }
 //n:一共有几个人参加游戏
 //m:报数到m的人,自杀(节点释放)
int ysf(int n, int m ) {
    // 创建不带头的单向循环链表
    ListNode*prev = Greatelist(n);
    //对该链表进行约瑟夫游戏
    ListNode*cur = prev->next;//就是头节点
    int count = 1;//从1开始报数
    while(cur->next!=cur)
    {
        if(count == m)
        {
            //删除节点
            //前一个节点指向大后面的节点
            prev->next = cur->next;
            free(cur);
            cur = prev->next;
            count = 1;//从新开始从1报数
        }
        else {
        //继续往下报数
        prev = cur;
        cur = cur->next;
        count++;
        }
    }
    //此链表中只有一个节点
    return cur->val;
}

Summarize

Okay, this blog ends here. If you have a better point of view, please leave a message in time. I will watch it carefully and learn from it.
If you don’t accumulate steps, you can’t reach a thousand miles; if you don’t accumulate small streams, you can’t become a river or sea.

Guess you like

Origin blog.csdn.net/2301_79585944/article/details/134897316