约瑟夫环是一个数学的应用问题:已知n个人(以编号1,2,3...n分别表示)围坐在一张圆桌周围。从编号为k的人开始报数,数到m的那个人出列;他的下一个人又从1开始报数,数到m的那个人又出列;依此规律重复下去,直到圆桌周围的人全部出列。
由题可知,使用循环链表解决比较方便。
#include<iostream>
using namespace std;
struct Node
{
int num;
Node *next;
};
int main()
{
int _num,m;
cout<<"the number of people and m:";
cin>>_num>>m;
Node *head=NULL;
Node *tail=NULL;
for (int i=1;i<=_num;i++)
{
Node *p = new Node;
p->num=i;
if (i==1)
{
head=p;
tail=p;
}
else
{
tail->next=p;
tail=p;
}
}
tail->next=head;
while(head)
{
Node *p=head;
for (int i=0;i!=m-2;i++)
{
p=p->next;
}
Node *_p=p->next;
p->next=_p->next;
cout<<_p->num<<endl;
delete _p;
_p=NULL;
head=p->next;
if (p->next==p)
{
cout<<p->num;
break;
}
}
return 0;
}