
👑个人主页:啊Q闻
🎇收录专栏:《数据结构》
🎉道阻且长,行则将至
前言
今天这道题目时牛客上的题目,名为环形链表的约瑟夫问题,很有趣的的一道题目
环形链表的约瑟夫问题
题目为:
 
思路:
看题目后我们明显知道这里要创建一个环形链表,我们首先要写一个函数,创建新节点,再由新节点来创造新链表;其次我们还要完成的步骤是逢m删除当前节点。
代码如下:
#include<stdlib.h>
 typedef struct ListNode ListNode;
 ListNode*BuyNode(int x)//创建新节点
 {
    ListNode*newnode=(ListNode*)malloc(sizeof(ListNode));
    if(newnode==NULL)
          exit(1);
          newnode->val=x;
          newnode->next=NULL;
          return newnode;
 }
 ListNode*createList(int n)//创建新链表
 {
    ListNode*phead=BuyNode(1);
    ListNode*ptail=phead;
    for(int i=2;i<=n;i++)
    {
        ptail->next=BuyNode(i);
        ptail=ptail->next;
    }
    ptail->next=phead;
    return ptail;
 }
int ysf(int n, int m ) {
    ListNode*prev=createList(n);
    ListNode*pcur=prev->next;
    int count=1;
    while(pcur->next!=pcur)//逢m删除当前节点
    {
        if(count==m)
        {
            prev->next=pcur->next;
            free(pcur);
            pcur=prev->next;
            count=1;
        }
        else {
        prev=pcur;
        pcur=pcur->next;
        count++;
        }
    }
     return pcur->val;
}详解:
创建新节点:
创建新链表:
逢m删除当前节点:
注意:
感谢阅读,对你有帮助的话,宝子们三连支持一下吧 ❤

















![[深度学习]yolov8+pyqt5搭建精美界面GUI设计源码实现一](https://csdnimg.cn/release/blog_editor_html/release2.3.6/ckeditor/plugins/CsdnLink/icons/icon-default.png?t=N7T8)



