双链表解决Josephus问题

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
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值