/*#include<iostream>
using namespace std;
struct jos
{
int bianhao;
int mima;
struct jos *next;
}*p,*q,*head;
int main()
{
int m,n,i,j;
cout<<"请输入人数 n:";
cin>>n;
for(i=1;i<=n;i++)
{
if(i==1)
{
head=p=(struct jos*)malloc(sizeof(struct jos));
if(p==0)
return 0;
}
else
{
q=(struct jos*)malloc(sizeof(struct jos));
if(q==0)
return 0;
p->next=q;
p=q;
}
cout<<"请输入第 "<<i<<" 个人的密码: ";
cin>>(p->mima);
p->bianhao=i;
}
p->next=head; //使链表尾指向链表头 形成循环链表
p=head;
cout<<"请输入m的初始值 m:";
cin>>m;
cout<<"出列顺序为: ";
for (j=1;j<=n;j++)
{
for(i=1;i<m;i++,p=p->next);
m=p->mima;
cout<<p->bianhao<<" ";
p->bianhao=p->next->bianhao;
p->mima=p->next->mima;
q=p->next;
p->next=p->next->next;
free(q);
}
cout<<endl;
return 0;
}
*/
#include <iostream>
using namespace std;
typedef struct LNode
{
int data;
struct LNode *link;
}LNode, *LinkList;
void Josephus(int n, int k, int m) // n个人,从第k个人开始报数,m为出列者喊到的数
{
LinkList p, r, cur; // p为当前结点,r为p的前驱
p = new LNode;
if(!p)
{
cout << "The failure of memory allocated!" << endl;
}
p->data = n;
p->link = p; //循环链表
cur = p;
for(int i=1; i<n; i++)
{
LinkList t = new LNode;
if(!t)
{
cout << "The failure of memory allocated!" << endl;
}
t->data = i;
t->link = cur->link;
cur->link = t;
cur = t;
}
//移动当前指针到k
while(k--)
{
r = p;
p = p->link;
}
//报数为m的人出列
while(n--)
{
for(int s=m-1; s--; r=p, p = p->link);
cout << "The output is: " << p->data << endl;
r->link = p->link;
LinkList d = new LNode;
if(!d)
{
cout << "The failure of memory allocated!" << endl;
}
d = p;
p = r->link;
delete d;
}
}
int main()
{
Josephus(13,4,1);
return 0;
}