题目描述
链表求解约瑟夫(Joseph)问题。有n个小孩围成一圈,给他们从1开始依次编号,从编号为1的小孩开始报数,数到第m个小孩出列,然后从出列的下一个小孩重新开始报数,数到第m个小孩又出列,…,如此反复直到所有的小孩全部出列为止,求整个出列序列。
如当n=6,m=5时的出列序列是5,4,6,2,3,1。
输入
n m的值
输出
出列序列
样例输入
6 5
样例输出
5 4 6 2 3 1
#include<iostream>
#include<string>
using namespace std;
int x=1;
struct node
{
int num;
node *next;//定义结构体
}*head;
int main()
{
int n,m;
cin>>n>>m;
head=new node();
node *s,*r,*p,*pre;
int i;
r=head;
for(i=0;i<n;i++)//尾插法
{
s=new node();
s->num=x;
x++;
r->next=s;
r=s;
}
r->next =head->next;//使最后一个节点指向第一个节点
p=head;
for(int j=0;j<n;j++)
{
for(int k=0;k<m-1;k++)
{
p=p->next ;
}//p为要去小孩的前一个
cout<<p->next->num<<" ";
p->next=p->next->next;去掉p后面的那个小孩
}
// system("pause");
return 0;
}