题目链接:点击打开链接
题目背景
约瑟夫是一个无聊的人!!!
题目描述
n个人(n<=100)围成一圈,从第一个人开始报数,数到m的人出列,再由下一个人重新从1开始报数,数到m的人再出圈,……依次类推,直到所有的人都出圈,请输出依次出圈人的编号.
输入格式:
n m(m,n≤100)
输出格式:
出圈的编号
输入样例
10 3
输出样例
3 6 9 2 7 1 8 5 10 4
思路:
很简单的题目,但是考察的应该是链表的基础
code:
#include<iostream>
using namespace std;
struct node
{
int date;
node * next;
};
int n,m;
void create(node * &head)//建造链表
{
node *q,*l;
l=head;
for(int i=1; i<n; ++i)
{
q=new node;
q->date=i;
if(head==NULL)
head=q;
else
l->next=q;
l=q;
}
q=new node;
q->date=n;
l->next=q;
l=q;
l->next=head;//设置循环链表
}
void show(node *head)//遍历
{
int i=0;
int t=0;
node *p=head;
while(t<n)
{
++i;
if(i==m-1)
{
node *s=p->next;
if(t==n-1)
cout<<s->date;
else
cout<<s->date<<" ";
p->next=s->next;
delete s;
++t;
i=0;
}
p=p->next;
}
}
int main()
{
node * head;
cin>>n>>m;
if(m+n==0)//有特殊情况
return 0;
head=NULL;
create(head);
show(head);
cout<<endl;
delete head;
return 0;
}
silum, n \le 100