使用双向循环链表解决约瑟夫问题
来源:互联网 发布:腾讯云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
- 使用双向循环链表解决约瑟夫问题
- 双向循环链表解决Josephus(约瑟夫)问题
- 双向链表解决约瑟夫问题
- 使用循环单链表解决约瑟夫环问题
- 使用循环单链表解决约瑟夫环问题
- 循环链表解决约瑟夫问题
- 循环链表解决约瑟夫环问题
- 循环链表解决约瑟夫环问题
- 用循环链表解决约瑟夫问题
- 用循环链表解决约瑟夫问题
- 循环链表解决约瑟夫环问题
- POJ3750 循环链表解决约瑟夫问题
- 循环链表解决约瑟夫环问题
- C语言通过双向循环链表解决Josephus(约瑟夫)问题
- 约瑟夫问题 java解法(双向链表解决)
- 用单向循环链表解决约瑟夫环问题
- 用个循环链表解决约瑟夫环问题
- [转]用单向循环链表解决约瑟夫环问题
- win7下安装linux(CentOS)过程中遇到的问题总结
- Jenkins+Gitlab搭建CI持续集成架构
- 内核与内核模块:depmod,lsmod,modinfo,insmod,rmmod,mdprobe
- CSDN-markdown编辑器 说明
- 虚函数
- 使用双向循环链表解决约瑟夫问题
- Gitlab CI Multi Runner搭建CI持续集成环境
- ubuntukylin系统下的Retext 的安装与配置
- 动态规划之最少硬币凑钱问题
- [前端插件]Bootstrap Table服务器分页与在线编辑应用总结
- 在Windows里使用Docker
- plsql
- UOJ 34 多项式乘法
- java--用户管理(前端+后台)