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

环形链表的约瑟夫问题

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

/**
 * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
 *
 * 
 * @param n int整型 
 * @param m int整型 
 * @return int整型
 */
 typedef struct listnode
 {
    int val;
    struct listnode*next;
 }listnode;
 listnode*Buynode(int n)
 {
    listnode*newnode = (listnode*)malloc(sizeof(listnode));
    newnode->val =n;
    newnode->next = NULL;
    return newnode; 
 }
void DelList(listnode**pcur)
{
    listnode*pf = (*pcur)->next;
    (*pcur)->val = pf->val;
    (*pcur)->next = pf->next;
}
int ysf(int n, int m ) {
    listnode*phead = NULL;
    listnode*ptail = NULL;
    phead = ptail =Buynode(1);
    int i = 0;
    for(i=2;i<=n;i++)
    {
        ptail->next = Buynode(i);
        ptail = ptail->next;
    }
    ptail->next = phead;
    listnode*pcur = phead;
    int count = 1;
    while(pcur->next->val != pcur->val )
    {
        ++count;
        pcur = pcur->next;
        if(count==m)
        {
            DelList(&pcur);
            count = 1;
        }
    }
    return pcur->val;
     

}

全部评论

相关推荐

1 收藏 评论
分享
牛客网
牛客企业服务