您的位置:首页 > 编程语言 > C语言/C++

用链表实现约瑟夫问题(c/C++)

2014-11-09 17:15 204 查看
约瑟夫问题:n个小孩围成一圈做游戏,给定一个数m,先从第s个小孩开始顺时针计数,每数到m,该小孩出列,然后从下一个小孩开始,数到m时

该小孩出列,如此反复,直到最后一个小孩,用链表解决约瑟夫问题
#include<iostream>
using namespace std;
#include<Cstring>
struct LNode
{
int no;
struct LNode *next;
};
int main()
{
int n,m,s;
cout<<"n=";
cin>>n;
cout<<"m=";
cin>>m;
cout<<"s=";
cin>>s;
LNode *first,*last;
first=last=new LNode;
first->no=1;
int i,k,c;
for(i=1;i<n;i++)//构造链表
{
LNode *p=new LNode;
p->no=i+1;
last->next=p;
last=p;
}
last->next=first;//构成环形链表
for(i=1;i<s;i++)//第s个孩子作为开始计数的小孩
{
first=first->next;
last=last->next;
}
k=n;
while(k>1)
{
for(c=1;c<m;c++)
{
first=first->next;
last=last->next;
}
last->next=first->next;//第m个孩子出列
cout<<first->no<<"\t";
delete first;
first=last->next;
k--;
}
cout<<endl<<"The winner is No"<<first->no;
delete first;
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: