约瑟夫环(c++版)

问题描述


约瑟夫环(约瑟夫问题)是一个数学的应用问题:已知n个人(以编号1,2,3…n分别表示)围坐在一张圆桌周围。从编号为1的人开始报数,数到m的那个人出列;他的下一个人又从1开始报数,数到m的那个人又出列;依此规律重复下去,直到圆桌周围的人全部出列。通常解决这类问题时我们把编号从0~n-1,最后 [1] 结果+1即为原问题的解。

代码实现


typedef struct Jose{
    int num;
    Jose* next;
}Jose;
//n个人,数到m停止
void initAndGetJose(int n,int m){
    if (m == 1) {
        for (int i =1 ; i<=n; i++) {
            cout<<i<<" ";
        }
    }
    else{
        Jose *first = new Jose;
        first->next = first;
        first->num =1;
        Jose *p =first;
        for (int i =2; i<= n; i++) {
            Jose *cur = new Jose{i,p->next};
            p->next =cur;
            p=p->next;
        }
        //1234  3
        //4124  2
        //4141  4
        //1111  1
        int count =n;
        Jose* pre = first;

        Jose* cur = first->next;

        while (count>0) {
            for (int i =2; i<m; i++) {
                pre=pre->next;
                cur=cur->next;
            }
            Jose* deleteNode = cur;
            cout<<deleteNode->num<<" ";
            pre->next = cur->next;
            pre = pre->next;
            cur = pre->next;
            delete deleteNode;
            count--;
        }
    }

}

猜你喜欢

转载自blog.csdn.net/opooc/article/details/81151050