#include <iostream> usingnamespace std; class Joseph{ protected: int number_of_people; int step; public: virtualvoid CreateOutput() =0; Joseph(){ number_of_people =0; step =0; } Joseph(int n,int m){ number_of_people = n; step = m; } }; class JosephWithLinkedlist; class Node{ int data; Node *link; public: Node(int ); Node(int ,Node*); Node* InsertAfter(int c); friend class JosephWithLinkedlist; }; Node::Node(int b){ data = b; link = NULL; } Node::Node(int b,Node *next){ data = b; link = next; } Node* Node::InsertAfter(int c){ link =new Node(c,link); return link; } class JosephWithLinkedlist:public Joseph{ public: JosephWithLinkedlist(int n,int m); JosephWithLinkedlist(const JosephWithLinkedlist &other); JosephWithLinkedlist&operator= (const JosephWithLinkedlist &other); //~JosephWithLinkedlist(); void CreateOutput(); private: Node *theList; }; JosephWithLinkedlist::JosephWithLinkedlist(int n,int m):Joseph(n,m){ Node *p,*q; theList =new Node(1); p = theList; p->link = theList; for(int i =2;i <= n;i++){ q =new Node(i); p->link = q; q->link = theList; p = q; } } JosephWithLinkedlist::JosephWithLinkedlist(const JosephWithLinkedlist &other){ number_of_people = other.number_of_people; step = other.step; Node *p =new Node(1); Node *f = p; f->link = p; for(Node *q = other.theList->link;q != theList;q = q->link){ f = f->InsertAfter(q->data); } theList = p; } // 赋值函数 JosephWithLinkedlist & JosephWithLinkedlist::operator= (const JosephWithLinkedlist &other){ // (1) 检查自赋值 if (this==&other) return*this; // (2) 释放原有的内存资源 Node *x; while (theList->link != theList){ x = theList->link; theList->link = x->link; delete x; } delete theList; // (3)分配新的内存资源,并复制内容 number_of_people = other.number_of_people; step = other.step; Node *p =new Node(1); Node *f = p; f->link = p; for (Node *q = other.theList->link;q != theList;q = q->link){ f = f->InsertAfter(q->data); } theList = p; // (4)返回本对象的引用 return*this; } void JosephWithLinkedlist::CreateOutput(){ Node *p = theList; Node *q = theList; for(int k =1;k <= number_of_people-1;k++) q = q->link; for(int i =1;i <= number_of_people;i++){ for(int j =1;j<step;j++){ p = p->link; q = q->link; } cout<<p->data<<endl; q->link = p->link; delete p; p = q->link; } } int main(){ int n,m; cout<<"Input the number of people:"<<endl; cin>>n; cout<<"Input the steps:"<<endl; cin>>m; cout<<endl; JosephWithLinkedlist a(n,m); a.CreateOutput(); return0; }