题解 | 环形链表的约瑟夫问题

环形链表的约瑟夫问题

https://www.nowcoder.com/practice/41c399fdb6004b31a6cbb047c641ed8a

/**
 * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
 *
 * 
 * @param n int整型 
 * @param m int整型 
 * @return int整型
 */
struct ListNode* buyNode(int x){
    struct ListNode* node = (struct ListNode*)malloc(sizeof(struct ListNode));
    node -> val = x;
    node -> next = NULL;
    return node;
}

struct ListNode* createCircle(int n){
    struct ListNode *phead =  buyNode(1);
    struct 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 ) {
    // write code here
    struct ListNode * prev = createCircle(n);
    struct ListNode * pcur = prev -> next;
    int count = 1;
    while(pcur -> next != pcur){
        if(count == m){
            prev -> next = pcur -> next;
            free(pcur);
            pcur = prev -> next;
            count = 1;
        }else{
            prev = pcur;
            pcur = pcur -> next;
            count ++;
        }
    }
    return pcur -> val;
}

全部评论

相关推荐

01-30 09:45
燕山大学 Java
喵_coding:这种直接跑就完事了 哪有毕业了才签合同 任何offer和三方都没有的
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务