用链表实现的,在vc2003中编译通过
struct Node
{
int value;
Node * next;
};
Node * head=NULL;
Node * end=NULL;
void Create()
{
Node * ps;
ps=new Node;
ps->value=i++;
if(head==NULL)
head=end=ps;
else
end->next=ps;
end=ps;
end->next=NULL;
}
void Josephus(int n,int m ,int s)
{
for(int i=0;i<n;i++)
Create();
//int j,k;
Node * p,*q,*temp;
p=q=head;
while(p->next)
{
p=p->next;
}
p->next=head;
if(m==0)
{
cout <<"错误的数目" <<endl;
return;
}
p=head;
if(s<1||s>n)
{
cout <<"错误的开始位置" <<endl;
return;
}
for(int i=1;i<s;i++)
p=p->next;
while(p!=p->next)
{
for(int i=1;i<m;i++)
{
q=p;
p=p->next;
}
q->next=p->next;
temp=p;
p=q->next;
delete temp;
}
cout <<"Winner is :" <<p->value <<endl;
}
本文介绍了一种使用链表来实现约瑟夫环问题的方法,并提供了完整的C++代码示例。通过创建一个循环链表,模拟了约瑟夫环问题中的报数淘汰过程。
6342

被折叠的 条评论
为什么被折叠?



