约瑟夫问题

来源:互联网 发布:樱井知香痉挛场景 编辑:程序博客网 时间:2024/06/05 13:58
#ifndef __JOSEPH_H_#define __JOSEPH_H_#include <iostream>using namespace std;struct Child{    int no;    Child *next;};class Joseph{public:    Joseph(int n1, int m1);    ~Joseph();    void Resolution();private:    int n,m;    Child *h;};//Joseph::Joseph(int n1, int m1){    int i;    n = n1;    m = m1;    Child *p, *r;    h = new Child;    h->no = 1;    r = h;    for( i = 2; i <= n; ++i)    {        p = new Child;        p->no = i;        r->next = p;        r = p;    }    r->next = h;}Joseph::~Joseph(){    Child *p;    p = h->next;    while(p!=h)    {        h->next = p->next;        delete p;    }    delete h;}//void Joseph::Resolution( ){    int i, j;    Child *p, *q;    for(i=1; i<n; ++i)    {        p = h;        j = 1;        while(j<m-1)        {            ++j;            p = p->next;        }        q = p->next;        cout<<q->no<<"  ";        p->next = q->next;        delete q;        h = p->next;    }}#endif // __JOSEPH_H_#include "Joseph.h"int main(){    int n=6, m=5;    Joseph obj(n,m);    obj.Resolution();    cout<<endl;    return 0;}

0 0
原创粉丝点击