### 题目描述
有n个人,编号为1~n,围成一个圈,从第一个人开始报数,报到m的出列,再由下一个人开始从1往后报,直到所有人出列,请依次输出出列人的编号
#### 样例
输入:10 3
输出:3 6 9 2 7 1 8 5 10 4
单纯想看报数问题的解的可以看我上一篇
这里主要分析单向、双向链表的构建与操作
单向链表:
#include<iostream>
using namespace std;
//用结构体数组实现单向静态链表
const int N = 100; //定义单向链表的大小
struct node {
int id;
int nextid;
}nodes[N];
int main()
{
int n, m;
cin >> n >> m;
nodes[0].nextid = 1;
for (int i = 1;i <= n;i++)
{
nodes[i].id = i;
nodes[i].nextid = i + 1;
}
nodes[n].nextid = 1; //构建循环链表
int now = 1, prev = 1;
while ((n --) > 1)
{
for (int i = 1;i < m;i++)
{
prev = now;
now = nodes[now].nextid;
} //到now指向m
cout << nodes[now].id << " ";
nodes[prev].nextid = nodes[now].nextid; //删除now
now = nodes[prev].nextid;
}
cout << nodes[now].id;
}
双向链表:
//用结构体数组实现双向链表
#include<iostream>
using namespace std;
const int N = 100;
struct node {
int id;
int preid, nextid;
}nodes[N];
int main()
{
int n, m;
cin >> n >> m;
nodes[0].nextid = 1; //头节点不储存数据
for (int i = 1;i <= n;i++)
{
nodes[i].id = i;
nodes[i].nextid = i + 1;
nodes[i].preid = i - 1;
}
nodes[n].nextid = 1;
nodes[1].preid = n; //循环,头的前为尾,尾的后一个为头
int now = 1;
while ((n--) > 1)
{
for (int i = 1;i < m;i++)
{
now = nodes[now].nextid;
}
cout << nodes[now].id << " ";
int pre = nodes[now].preid;
int next = nodes[now].nextid;
nodes[pre].nextid = nodes[now].nextid;
nodes[next].preid = nodes[now].preid; //删除now节点
now = next; //后移一位
}
cout << nodes[now].id;
}