使用双向循环链表解决约瑟夫问题
2016-09-30 23:09
357 查看
#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, done if (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; }
相关文章推荐
- C语言通过双向循环链表解决Josephus(约瑟夫)问题
- 使用jackson转json解决双向关联循环调用
- 用双循环链表解决约瑟夫问题
- 循环双向链表 及 约瑟夫问题的解决
- 双向循环链表-解决顺逆时针约瑟夫环
- 用上节的循环双向链表解决vigenere加密问题。
- 使用jackson转json解决双向关联循环调用
- hibernate双向关联和json-lib使用的死循环问题的解决
- STL--> list 双向循环链表容器 接口使用及介绍。 模拟实现 STL list容器
- 迭代器的使用之双向循环链表
- 数据结构三:循环链表解决约瑟夫问题实现
- C++数据结构--循环链表的应用--解决约瑟夫问题
- 使用C#循环链表解决约瑟夫环的问题
- 用单向循环链表解决约瑟夫问题
- 双向循环链表的删除
- VxWorks下使用双向链表的小例子
- 双向循环链表的实现(粗糙版)
- 双向循环链表