也是无聊吧。用面向对象加单链表解决一下约瑟夫问题。 个人声明:只做娱乐,加练练手。 #include <iostream> #include <string> using namespace std; class List;//声明List类 class Person { private: int num; char* name; Person *next;//圈中下一个人 static int count; public: Person(); ~Person(); void setName(char na[]); char* getName(); int getNum(); friend class List; }; class List { private : Person *head,*tail;//无头节点链表 public : List() { head=NULL; tail=NULL; } void addPerson(Person *person); Person* delePerson(Person *person,int n); void dispPerson(); }; int Person::count=0; Person::Person() { name=new char[10]; count++; num=count; } Person::~Person() { count--; cout<<this->name<<" is delete ..."<<endl; delete[] this->name; } void Person::setName(char na[]) { strcpy(name,na); } char* Person::getName() { return this->name; } int Person::getNum() { return this->num; } void List::addPerson(Person *person) { if(head==NULL) { tail=head=person; head->next=head; return; } person->next=tail->next; tail->next=person; tail=person; } //删除从p数起的第n-1个人 Person* List::delePerson(Person *person,int n)//返回删除人员的下一个 { if(head==NULL) { cout<<"error:no person to leave"<<endl; return NULL; } Person *p=head,*pre=tail;//pre为p的前一个人 while(p!=person)//寻找p { if(p==tail) { cout<<"error:can't find person who num="<<person->num<<endl; return NULL; } pre=p; p=p->next; } //寻找删除人员 for(int i=0;i<n-1;i++) { pre=p; p=p->next; } pre->next=p->next; if(p==head) head=p->next; if(p==tail) tail=pre; if(p->next==p) { head=tail=NULL; return NULL; } cout<<p->name<<" out"<<endl; return p->next; } void List::dispPerson() { Person *p=head; while(p!=tail) { cout<<"name:"<<p->name<<" num="<<p->num<<" p->next"<<p->next->num<<endl; p=p->next; } cout<<"name:"<<tail->name<<" num="<<tail->num<<" tail->next:"<<tail->next->num<<endl; } int Joseph() { List l; Person *persons,*p; int i,n,length;//n参加人数,length报数长度 cout<<"input the numble of person:"<<endl; cin>>n; persons=new Person[n]; cout<<"input the name of person in turns:"<<endl; for(i=0;i<n;i++) { char name[10]; cin>>name; persons[i].setName(name); l.addPerson(persons+i); } l.dispPerson(); cout<<"input the length:"<<endl; cin>>length; if(length<=0) { cout<<"大哥你玩我吧!!!"<<endl; return -1; } p=persons; for(i=0;i<n;i++) { if(p==NULL) return -1; p=l.delePerson(p,length); } delete[] persons; return 1; } void main() { Joseph(); }