约瑟夫环-顺序表 https://blog.csdn.net/qq_46457493/article/details/124362024
约瑟夫环-循环单链表
#include<iostream>
using namespace std;
struct yue
{
int data;
yue *next;
};
class fu
{
public:
fu();
fu(int n);
~fu();
void k(int m);
private:
yue *first;
};
fu::fu()
{
first=new yue;
first->next=NULL;
}
fu::fu(int n)
{
try
{
first=new yue;
if(n==0)throw"长度参数非法";
yue *s,*r;
r=first;
for(int b=0;b<n;b++)
{
s=new yue;
r->next=s;
s->data=b+1;
r=s;
}
r->next=first;
}
catch(char *s)
{cout<<s<<endl;}
}
fu::~fu()
{
delete first;
}
void fu::k(int m)
{
try
{
if(m==0)throw"密码参数非法";
yue *r,*s;
int b=0;
r=first;
cout<<"出环顺序为: ";
for(;first->next!=first;)
{
if(b==m)
{
cout<<r->data<<" ";
s->next=r->next;
delete r;
r=s->next;
b=1;
}
else
{
s=r;
r=r->next;
if(r!=first)b++;
}
}
cout<<endl;
}
catch(char *s)
{cout<<s<<endl;}
}
int main()
{
int n,m;
cout<<"请输入约瑟夫环长度: ";
cin>>n;
cout<<"请输入密码: ";
cin>>m;
fu L(n);
L.k(m);
return 0;
}