#include<bits/stdc++.h>
using namespace std;
struct node
{int num;//记录这个结点对应猴子的编号
node *next,*pre;//next指向结点的后继,pre指向结点的前驱
}*head,*tail,*p;//head表示头指针,tail表示尾指针
int n,m;
int main()
{
while(cin>>n>>m,n||m)//判断n,m是否为0 0
{
head=new node;
head->num=1;
head->next->pre=NULL;
tail=head;//先建立编号为1的结点,头指针和尾指针此时都指向它
for(int i=2;i<=n;i++)
{
p=new node;
p->num=i;//建立编号为i的结点
tail->next=p;
p->pre=tail;//将p指向的结点插入到tail指向的结点的后面
p->next=NULL;
tail=p;//将tail更新为p,下次就插入到它的后面
}
head->pre=tail;
tail->next=head;//因为是循环链表,所以头尾项链
p=head;
for(int i=1;i<n;i++)//因为我们要输出剩下的最后一个的编号
{//所以只要循环(n-1)次,每次删除一个结点,即可确定答案
for(int j=1;j<m;j++)
p=p->next;//经过(m-1)次,p指向要删除的那个结点
p->next->pre=p->pre;
p->pre->next=p->next;//删除结点p
p=p->next;//剩下的猴子就从刚刚删除的结点的后继开始报数
}
cout<<p->num<<endl;//最后剩余一个结点,则这个结点的编号即为答案
}
}
约瑟夫问题(链表)
于 2018-02-12 01:58:51 首次发布