郁闷,约瑟夫又有问题,
#include "stdafx.h"#include <iostream>using std::endl;using std::cout;template<typename T>class CirList{public: struct Node { T data; Node* next; Node(T const& ndata):data(ndata),next(NULL){} Node( ):next(NULL){} };private: Node* head; Node* tail;public: CirList() { head=new Node(); tail=NULL; } ~CirList() { Clear(); } void AddElem( T const& ndata) { Node* newNode= new Node(ndata); //插入元素 if(tail) { newNode->next=head->next; tail->next=newNode; head->next=newNode; } else { head->next=newNode; tail=newNode; newNode->next=newNode; } } void Clear() { Node* p=head->next; while(p) { Node* q=p; p=p->next; delete q; if(q==tail) break; } delete head; } void Print() const { Node* p=head->next; while(p) { cout<<p->data<<" "<<endl; if(p==tail) break; p=p->next; } } Node* GetHead() const { return head; } Node* GetTail() const { return tail; }};struct Jo{ int pos; bool flag; //是否被出局 //Jo(int nPos, bool bFlag):pos(nPos),flag(bFlag){} void SetPos(int nPos) { pos=nPos; } void SetFlag(bool bflag) { flag=bflag; }};class ResolveJo{ CirList<Jo> mylist; int step; int count;public: ResolveJo(int nStep, int nCount):step(nStep),count(nCount){}private: bool Check(int &nPos) //检测是否已经找到了 { CirList<Jo>::Node * head =mylist.GetHead(); CirList<Jo>::Node* tail=mylist.GetTail(); int n=0; head=head->next; //跳过哨兵节点 nPos=0; while(head) { if(! head->data.flag) n++; else { nPos=head->data.pos; } if(head==tail) break; head=head->next; } if(n==count-1) return true; return false; }public: void Solution() //解决约瑟夫问题 { int i; for(i=0; i<count; i++) { Jo temp; temp.SetFlag(true); temp.SetPos(i); mylist.AddElem(temp); } int targetPos; int n=0; //开始寻找 CirList<Jo>::Node* head=mylist.GetHead(); CirList<Jo>::Node* tail=mylist.GetHead(); head=head->next; while(1) { if(Check(targetPos)) { cout<<targetPos<<endl; break; } if(head->data.flag) n++; if(n==step) { n=0; head->data.flag=false; } head=head->next; } }};int main(){ ResolveJo obj(2,7); //手动计算是6, 结果不是6,说明我的代码有问题啊。 obj.Solution(); return 0;}