约瑟夫问题--循环链表解决方案
Posted my-new-blog-zxj
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了约瑟夫问题--循环链表解决方案相关的知识,希望对你有一定的参考价值。
//头文件circlelist.h #pragma once #ifndef CIRCLELIST_H_ #define CIRCLELIST_H_ #include<iostream> using namespace std; struct circleNode{ float data; circleNode* next; }; class circleList { private: int size; circleNode* first; circleNode* last; public: circleList(circleNode* newlist=NULL) { first = newlist; }; //循环链表的实现方法 bool insert(float a,int i);//插入,a为插入的数,i为插入的位置。 bool remove(int i);//删除第i个位置的节点 circleNode* findPtr(int i);//返回第i个结点的地址 }; #endif // !CIRCLELIST_H_
//源文件circlelist.cpp #include"circlelink.h" bool circleList::insert(float a, int x) { circleNode* newlist = new circleNode; if (newlist == NULL) { cerr << "内存分配错误!" << endl; return false; }; newlist->data = a; if (first == NULL) { this->first = newlist; newlist->next = first; last = newlist; size = 1; } else { last->next = newlist; newlist->next = first; last = newlist; size++; } return true; } bool circleList::remove(int i) { if (i > size || first == NULL||i<1) { cerr << "空表或位置错误!" << endl; return false; } else { circleNode* current = first; if (i>1) { current=this->findPtr(i-1); //current指向i-1。 circleNode* del=current->next; if (del == last) { last = current; } current->next = del->next; delete del; size--; return true; }else { circleNode* n = first->next; delete first; first = n; } } } circleNode* circleList::findPtr(int i) { circleNode* current = first; if (i > size || first == NULL||i<=0) { cerr << "未找到元素!" << endl; }else { for (int j = 1; j < i; j++) { current = current->next; } return current; } }
//主文件 #include <iostream> #include"circlelink.h" //约瑟夫问题,n--总人数,s---起始位置,m--第几个淘汰 bool josephus(circleList* list,int n,int s,int m) { circleNode* current = list->findPtr(s); circleNode* pre=NULL; if (m <= 0) { cerr << "输入有误!" << endl; return false; } for(int x=0;x<n-1;x++){ for (int j = 1; j < m; j++) { pre = current; current = current->next; } cout << current->data << "淘汰了!" << endl; pre->next = current->next; delete current; current = pre->next; } return true; } int main() { circleList list; for (int i = 1; i < 10; i++) { list.insert(i,i); } josephus(&list,9,1,10); }
以上是关于约瑟夫问题--循环链表解决方案的主要内容,如果未能解决你的问题,请参考以下文章