//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ //方法四:面向对象的实现 //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ //ring.h //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ struct Node { int code; Node *next; };
class Ring { public: Ring(int n); ~Ring(); void Progress(int m); void PrintNode(); void ClearCode(); protected: Node *head; Node *pivot; Node *pCur; }; //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ //ring.cpp //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ #include #include #include "ring.h" Ring::Ring(int n) { head = new Node[n]; pCur = head; for (int i=1; i<=n; i++,pCur=pCur->next) { pCur -> code = i; pCur -> next = head + (i % n); // PrintNode();//if you want to look the boy who was you input,you can live out "//" } cout< pCur = &head[n-1]; } Ring::~Ring() { delete []head; } void Ring::Progress(int m) { for (int i=0; i { pivot = pCur; pCur = pCur -> next; } } void Ring::PrintNode() { static int lineCount; if (((lineCount++) % 10) == 0) cout< cout << setw(4) << pCur -> code; } void Ring::ClearCode() { pivot->next=pCur->next; pCur=pivot; } //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ //jose.h //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ class Jose { public: Jose(int boys=10, int begin=1, int m=3); void Initial(); void GetWinner(); protected: int numOfBoys; int beginPos; int interval; }; //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ //Jose.cpp //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ #include #include "ring.h" #include "Jose.h" Jose::Jose(int boys , int begin, int m) { if (boys < 1) { cout << "Bad number of boys!/n"; return; } if (begin < 0) { cout << "Bad beginning position!/n"; return; } if ((m<1) || (m>boys)) { cout << "Bad interval number!/n"; return; } numOfBoys = boys; beginPos = begin; interval = m; } void Jose::GetWinner() { Ring x(numOfBoys); x.Progress(beginPos); for (int i=1; i { x.Progress(interval); //x.PrintNode(); //if you want to look the boy who is out,you can live out "//" x.PrintNode(); x.ClearCode(); } cout<<"/nThe winner is:"; x.PrintNode(); } void Jose::Initial() { int num,begin,m; cout<<"Please input the number of boys,Beginning position,innterbal per count" < cin>>num>>begin>>m; if(num<2) { cerr<<"bad number of boys" < return; } if(begin<0) { cerr<<"bad beginning position." < return; } if(m<1||m>num) { cerr<<"bda interval number." < } numOfBoys=num; beginPos=begin; interval=m; } //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ //main.cpp //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ #include "Jose.h" void main() { Jose jose; jose.Initial(); jose.GetWinner(); } |