使用双向循环链表解决约瑟夫问题

来源:互联网 发布:腾讯云mysql 编辑:程序博客网 时间:2024/06/06 05:53
#include<iostream>using namespace std;class monkey {public:int No;monkey *next, * pre;monkey( int info,  monkey* preValue = 0,  monkey *nextValue = 0) {No = info;pre = preValue;next = nextValue;}monkey() {};};class MyList{//private:public:monkey *head;monkey *setPos(const int i);MyList(monkey* h) {//monkey tmp(0);head = h;head->No = 0;head->next = 0;head->pre = 0;}//~MyList();//bool isEmpty();//void clear();//int length();bool append(int value, monkey* tmp);bool remove(monkey* tmp);int getValue(const int i);};//find the ith componet of the myList;monkey* MyList::setPos(const int i) {int myCount = 0;if (i == -1) return head;monkey* p = head->next;while (p != 0 && myCount < i) {p = p->next;myCount++;}return p;}bool MyList::append(int value, monkey* tmp) {tmp = new monkey;tmp->No = value;//if this is a empty list, then add value after head;if (head->next == 0) {tmp->next = head;tmp->pre = head;head->next = tmp;head->pre = tmp;//cout << tmp->pre->pre->No << endl;//cout << "tmp=" << tmp << "  head=" << head << endl;}else {//if this list isn't empty, then add value between head and head->next;tmp->pre = head->pre;tmp->next = head;head->pre->next = tmp;head->pre = tmp;//cout << head->next->No << endl;//cout << "tmp=" << tmp << "  head=" << head << endl;}return 1;}int MyList::getValue(int i) {return setPos(i)->No;}bool MyList::remove(monkey* tmp) {tmp->next->pre = tmp->pre;tmp->pre->next = tmp->next;tmp->next = 0;tmp->pre = 0;free(tmp);return true;}int main() {int n = 0, m = 0;cin >> n >> m;monkey mhead(0);MyList MonkeyList(&mhead);monkey tmp(0);for (int i = 1; i < n+1; i++) {MonkeyList.append(i,&tmp);}int myCount = 0;monkey* curPoint = MonkeyList.setPos(0);while (1) {//if curPoint's next point is head, then there is only one point left, doneif (curPoint->next->No == 0 && curPoint->pre->No==0) {cout << curPoint->No << endl;break;}//if the curPoint is the head, then skip to next point;if (curPoint->No == 0) {curPoint = curPoint->next;continue;}myCount++;if (myCount == m) {int curNo = curPoint->No;monkey* nextPoint = curPoint->next;MonkeyList.remove(curPoint);curPoint = nextPoint;myCount = 0;}else {curPoint = curPoint->next;}}return 0;}

0 0