せいしゅん404 • 4年前
#include<cstdio>
#include<iostream>
using namespace std;
struct node{
int num;//数据域
node *pre,*next;//前后双向指针域
};
int main(void){
int n,m,s,d;
node *head,*p,*q,*rear;
cin>>n>>m;
//生成头节点
head=new node;
head->num=1;
head->next=NULL;
head->pre=NULL;
q=head;
//循环生成链表
for(int i=2;i<=n;i++){
p=new node;
p->next=NULL;
p->pre=NULL;
p->num=i;
q->next=p;//前一个节点与当前节点产生关联
p->pre=q;//当前节点与前节点产生关联
q=p;
}
rear=q;
p=head;
s=0;
d=1;//往右查找
while(head!=rear){
s++;
if(s==m){
s=0;
//这个人在尾结点
if(p==rear){
rear=p->pre;//更改尾结点标记
p=rear;//p重新指向新的尾结点
d=2;//改变方向往左查找
continue;
}
//这个人在头结点
if(p==head){
head=p->next;//更改头结点标记
p=head;//p重新指向新的头结点
d=1;//改变方向往右查找
continue;
}
//这个人在中间节点
p->pre->next=p->next;
p->next->pre=p->pre;
}
if(d==1){
//向右
if(p==rear){
p=p->pre;
d=2;
}else{
p=p->next;
}
}else{
//向左
if(p==head){
p=p->next;
d=1;
}else{
p=p->pre;
}
}
}
cout<<head->num<<endl;
return 0;
}
评论:
请先登录,才能进行评论