双链表解决Josephus问题

来源:互联网 发布:碧然德滤水壶 asa 知乎 编辑:程序博客网 时间:2024/06/06 16:44
Josephus问题是下面的这个游戏:

有N个人坐成一圈,编号为1至N。从编号为1的人开始传递热马铃薯。M次传递之后,持有热马铃薯的人退出游戏,圈缩小,然后游戏从退出人的下面的人开始,继续进行。最终留下来的人获胜。这样,如果M=0并且N=5,那么参加游戏的人依次退出,5号获胜。如果M=1并且N=5,那么退出的顺序就是2,4,1,5。


#include <iostream>using namespace std;struct Node{    int data;    Node *next;    Node *pre;    Node ( int d = 0, Node *n = NULL, Node *p = NULL )        : data ( d ), next ( n ), pre ( p ) {}} ;class Jose{public:    Jose()    {        init();    }    ~Jose()    {        delete head;        delete tail;    }    int size() const    {        return theSize;    }    void print() const    {        Node *h = head;        while ( h->next != tail )        {            h = h->next;            cout << h->data << " ";        }        cout << endl;    }    void push ( int x )    {        Node *n = new Node;        n->data = x;        n->next = head->next;        head->next->pre = n;        head->next = n;        n->pre = head;        theSize++;    }    void creat ( int Size )     {        for ( int i = Size; i > 0; i-- )            push ( i );    }    Node * pop ( Node *n )    {        Node *h = n->next;        h->pre = n->pre;        n->pre->next = h;        delete n;        theSize--; //出局,人数减1        if ( h == tail )            h = head->next;        return h;    }    void josephus ( int Size, int M )    {        creat ( Size );        Node *h = head->next;        int n;        while ( theSize > 1 )        {            n = M;            while ( n-- )            {                if ( h->next == tail )                    h = head;                h = h->next;            }            cout<<h->data<<" ";//输出出局的人            h = pop ( h );            //print();        }        cout << head->next->data << endl;//输出最后的数    }private:    int theSize;    Node *head;    Node *tail;    void init()    {        theSize = 0;        head = new Node;        tail = new Node;        head->next = tail;        tail->pre = head;    }};int main(){    Jose J  ;    J.josephus ( 20, 4 );    return 0;}


0 0
原创粉丝点击