約瑟夫環比較經典了
已知n個人(以編號1,2,3...n分別表示)圍坐在一張圓桌周圍。從編號
為k的人開始報數,數到m的那個人出列;他的下一個人又從1開始報數,
數到m的那個人又出列;依此規律重復下去,直到圓桌周圍的人全部出列。
測試過的完整實現代碼:
#include<iostream>
using namespace std;
struct node{
int num;
node *next;
};
node *creat(int n)
{
node *q,*p,*head=NULL;
for(int i=1;i<=n;i++)
{
p=new node;
p->num=i;
if(head==NULL)
head=p;
else
q->next=p;
q=p;
}
p->next=head;
return p;
}
int main()
{
int n,k,m;
cin>>n>>k>>m;
node *l,*q;
l=creat(n);
q=l;
l=l->next;
for(int i=1;i<k;i++)
{
q=l;
l=l->next;
}
while(l->next!=l)
{
for(int i=1;i<m;i++)
{
q=l;
l=l->next;
}
cout<<l->num<<"->";
q->next=l->next;
delete l;
l=q->next;
}
cout<<l->num<<endl;
delete l;
return 0;
}
