环形链表的约瑟夫问题(牛客网)

/**
 * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
 *
 * 
 * @param n int整型 
 * @param m int整型 
 * @return int整型
 */


struct ListNode * BuyNode(int n)//创建节点和成环
 { 
    struct ListNode  *phead=NULL;
    struct ListNode  *ptail=NULL;
    int N=1;
    while(n--){  
        struct ListNode *newnode=(struct ListNode *)malloc(sizeof(struct ListNode));
        newnode->val=N++;
        newnode->next=NULL;
         
        if(phead==NULL)
        {
            phead=ptail=newnode;
        }
        else{
            ptail->next=newnode;
            ptail=newnode;
        }
    }
    ptail->next=phead;
    return ptail;//返回尾节点
 }
 

int ysf(int n, int m ) {
    // write code here
     if(n == 1)
    {
        return n;
    }
    struct ListNode * tail = BuyNode(n);
    struct ListNode * cur = tail->next;
     
    int N = 1;
    while(cur->next != cur)
    {
        if(N == m)
        {
            tail->next = cur->next;
            cur = tail->next;
            N = 1;
        }
        N++;
        cur = cur->next;
        tail = tail->next;      
    }
     
    return cur->val;
}

相关推荐

  1. 环形问题

    2024-04-21 18:38:07       19 阅读
  2. C++ 环形(解决问题)

    2024-04-21 18:38:07       10 阅读

最近更新

  1. TCP协议是安全的吗?

    2024-04-21 18:38:07       19 阅读
  2. 阿里云服务器执行yum,一直下载docker-ce-stable失败

    2024-04-21 18:38:07       19 阅读
  3. 【Python教程】压缩PDF文件大小

    2024-04-21 18:38:07       19 阅读
  4. 通过文章id递归查询所有评论(xml)

    2024-04-21 18:38:07       20 阅读

热门阅读

  1. web大型工程项目架构以及搭建

    2024-04-21 18:38:07       17 阅读
  2. linux中ssh远程登陆

    2024-04-21 18:38:07       15 阅读
  3. Golang面试题五(GC)

    2024-04-21 18:38:07       18 阅读
  4. 动态库的制作和使用

    2024-04-21 18:38:07       15 阅读
  5. c++IO

    c++IO

    2024-04-21 18:38:07      14 阅读
  6. 什么是ProxySQL?

    2024-04-21 18:38:07       31 阅读
  7. 华为OD-C卷-执行任务赚积分[100分]C++ 100%

    2024-04-21 18:38:07       18 阅读