数据结构实践,这种实验对我来说都很纠结。代码为自编,如发现问题,欢迎指导。
约瑟夫环(Joseph)问题的一种描述是:编号为1、2、3……n的n个人按照顺时针方向围坐一圈,没人持有一个密码(正整数)。一开始任选一个正整数作为报数的上限值m,从第一个人开始按照顺时针的方向自1开始顺序报数,报到m时停止报数。报m的人出列,将他的密码作为新的m值,从他的顺时针方向上的下一个人开始重新从1报数,如此下去,直至所有人全部出列为止。试设计一个程序求出出列顺序。
#include "iostream"
using namespace std;
class people
{
public:
int cipher;
int number;
class people *next;
}p[7];
void create(int n)
{
cout<<"please input"<<endl;
for(int i=1;i<=n;i++)
{
p[i-1].number=i;
cin>>p[i-1].cipher;
p[i-1].next=&p[i];
if(i==n)
p[i-1].next=&p[0];
}
}
void show(int n)
{
cout<<"now show the list"<<endl;
for(int i=1;i<=n;i++)
{
cout<<p[i-1].number<<":"<<p[i-1].cipher<<endl;
}
}
int del(int m,int n)
{
people *p1;
p1=&p[0];
people *p2;
for(int i=1;i<=n;i++)
{
for(int j=0;j<m-1;j++)
{
p2=p1;
p1=p1->next;
}
m=p1->cipher;
cout<<p1->number<<":"<<p1->cipher<<endl;
p2->next=p1->next;
p1=p1->next;
}
return 0;
}
int main()
{
int m=20,n=7;
// people *p1;
create(n);
show(n);
cout<<"answer:"<<endl;
del(m,n);
return 0;
}