热度 2|
//maincpp
#include <iostream>
#include "MemberFuncion.h"
using namespace std;
int main()
{
int Pnum;
cout<<"输入约瑟夫问题的参与人数:"<<endl;
cin>>Pnum;
Person *pNode=new Person;
Init(&pNode,Pnum);
cout<<"他们按照这样的顺序站成了一圈:"<<endl;
show(pNode);
GameStart(&pNode);
return 0;
}
//MemberFunction.cpp
#include <iostream>
using namespace std;
struct Person
{
int num;
struct Person *next;
};
void Init(Person **pNode,int Pnum);
void show(Person *pNode);
void Kill(Person **pNode,Person *pKnife);
void GameStart(Person **pNode);
void Init(Person **pNode,int Pnum)
{
Person *p1=NULL,*p2=NULL;
p1=*pNode;
for(int i=1;i<=Pnum;i++)
{
p1->num=i;
p2=p1;
p1=new Person;
p2->next=p1;
}
p2->next=(*pNode);
p2=p1;
free(p1);
}
void show(Person *pNode)
{
Person *pread=pNode;
do
{
cout<<pread->num<<"->";
pread=pread->next;
}while(pread!=pNode);
cout<<endl;
}
void Kill(Person **pNode,Person *pKnife)
{
Person *temp=pKnife->next;
if(temp==(*pNode))
{
(*pNode)=(*pNode)->next;
pKnife->next=(*pNode);
}
else
{
pKnife->next=temp->next;
}
free(temp);
show(*pNode);
}
void GameStart(Person **pNode)
{
Person *pCur=(*pNode),*pKnife=NULL;
for(int i=1;;)
{
if(i%2==0)
{
cout<<"序号为"<<pCur->num<<"的人报数:"<<i<<endl;
cout<<"序号为"<<pCur->num<<"的人一刀杀死了排在他后面的人!其他人鼓掌!"<<endl;
pKnife=pCur;
pCur=pCur->next->next;
Kill(&(*pNode),pKnife);
i=1;
}
else
{
cout<<"序号为"<<pCur->num<<"的人报数:"<<i<<endl;
pCur=pCur->next;
i++;
}
if(pCur==pCur->next->next)
{
cout<<"剩下的这两个人,序号为:"<<pCur->num<<" "<<pCur->next->num;
cout<<"不用自杀了。"<<endl;
break;
}
}
}
小甲鱼: 目前日志暂没提供代码格式,论坛帖子就有哦~
小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)
GMT+8, 2024-5-13 10:37
Powered by Discuz! X3.4
© 2001-2023 Discuz! Team.