程序源代源如如下:
#include<iostream.h>
struct node
{
int data;
node *next;
};
class josephus
{
public:
josephus()
{
first=new node;
first->next=NULL;
}
josephus(int a[],int n);
~josephus(); //析构函数
void Delete(int i);
void print();
private:
node *first;
};
josephus::josephus(int a[],int n) //头播法建立单链表
{
first=new node;
first->next=NULL;
for(int i=0;i<n;i++)
{
node *s;
s=new node;
s->data=a[i];
s->next=first->next;
first->next=s;
}
}
josephus::~josephus()
{
node *p;
node *q;
p=first->next;
while(p)
{
q=p;
p=p->next;
delete q;
}
}
void josephus::Delete(int i)
{
node *p;
p=new node;
p=first;
int j=0;
int x=0;
while(p&&j<i-1)
{
p=p->next;
j++;
}
if(!p||!p->next) throw "位置";
else
{
node *q;
q=new node;
q=p->next;
x=q->data;
p->next=q->next;
//cout<<x;
delete q;
//return x;
}
}
void josephus::print()
{
node *s;
s=new node;
s=first->next;
while(s)
{
cout<<s->data<<endl;
s=s->next;
}
}
void main()
{
int *p,m,n;
cout<<"请输入总人数"<<endl;
cin>>m;
p=new int[m];
for(int i=0;i<m;i++)
p[i]=i;
josephus();
josephus t(p,m);
~josephus(); //此处的析构函数在编译时提示前面的符号不能识别
t.print();
cout<<"请输入第一个出队的人的位置"<<endl;
cin>>n;
cout<<"出队的顺序为"<<endl;
for(int j=0;j<m;j++) //按位册除 ??此处我用了一个for循环为什么就不行了呢?请高手指教
t.Delete(n);
}