#include <iostream>
using namespace std;
typedef struct node
{
int data;
struct node*next;
}node, *linklist;
node*creatlist(int n)//pushfront
{ int i;
linklist head,p;
head=(node*)malloc(sizeof(node));
if(!head)
{
exit(1);
}
head->data=1;
head->next=head;
for(i=n;i>1;--i)
{ p=(node*)malloc(sizeof(node));
if(!p)
{
exit(1);
}
p->data=i;
p->next=head->next;
head->next=p;
}
return head;
}
void traverse(linklist head)
{
linklist p=head;
do
{
cout<<p->data<<endl;
p=p->next;
}
while(p!=head);
}
void josephus(linklist head,int n,int b)
{
linklist p,q;
int c,k;
p=head; c=1; k=n;
while(k>1)
{
if(c==b-1)
{
q=p->next; p->next=q->next;
cout<<q->data<<" ";
free(q);
c=0; --k;
}
else {c++; p=p->next;}
}
cout<<"The winner is "<<p->data;
cout<<endl;
}
int main()
{ linklist head;
int n,b;
cout<<"please input how many people play"<<endl;
cin>>n>>b;
creatlist(n);
head=creatlist(n);
traverse(head);
josephus(head,n,b);
system("pause");
return 0;
}
josephus list
最新推荐文章于 2022-03-17 20:04:03 发布