环形链表的约瑟夫问题

环形链表的约瑟夫问题

一、 题目


1
1

二、思路

这个题的思路呢,就是建立一个环形链表,从1计数,计数到m就删除节点,然后返回最后的节点存的值,有个问题是,循环的结束条件是什么?这是一个难点,下面画图解决!!!
1
cur->next == cur时,循环结束。

/**
 * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
 *
 * 
 * @param n int整型 
 * @param m int整型 
 * @return int整型
 */
 struct ListNode* BuyNode(int x)
 {
    struct ListNode* newnode = (struct ListNode*)malloc(sizeof(struct ListNode));
    newnode->next = NULL;
    newnode->val = x;
    return newnode;
 }
 struct ListNode* CreatList(int n)
 {
    struct ListNode*  phead =BuyNode(1);
    struct ListNode*  tail = phead;
    for(int i = 2;i<n+1;i++)
    {
        struct ListNode*  newnode =BuyNode(i);
        //直接尾插
        tail->next = newnode;
        tail = newnode;
    }
    tail->next = phead;
    return phead;
 }
int ysf(int n, int m ) {
    // write code here
    struct ListNode*plist = CreatList(n);
    int count  = 1;
    struct ListNode* cur = plist;
    struct ListNode* prev = NULL;
    while(cur->next!=cur)
    {
        if(count == m)
        {
            prev->next = cur->next;
            free(cur);
            cur = prev->next;
            count = 1;
        }
        else {
            prev = cur;
            cur = cur->next;
            count++; 
        }
    }
    return cur->val;
}
/**
 * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
 *
 * 
 * @param n int整型 
 * @param m int整型 
 * @return int整型
 */
 struct ListNode* BuyNode(int x)
 {
    struct ListNode* newnode = (struct ListNode*)malloc(sizeof(struct ListNode));
    newnode->next = NULL;
    newnode->val = x;
    return newnode;
 }
 struct ListNode* CreatList(int n)
 {
    struct ListNode*  phead =BuyNode(1);
    struct ListNode*  tail = phead;
    for(int i = 2;i<n+1;i++)
    {
        struct ListNode*  newnode =BuyNode(i);
        //直接尾插
        tail->next = newnode;
        tail = newnode;
    }
    tail->next = phead;
    return tail;
 }
int ysf(int n, int m ) {
    // write code here
    struct ListNode*plist = CreatList(n);
    int count  = 1;
    struct ListNode* cur = plist->next;
    struct ListNode* prev = plist;
    while(cur->next!=cur)
    {
        if(count == m)
        {
            prev->next = cur->next;
            free(cur);
            cur = prev->next;
            count = 1;
        }
        else {
            prev = cur;
            cur = cur->next;
            count++; 
        }
    }
    return cur->val;
}

完结!!!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值