使用C++来解决约瑟夫环问题!
#include <iostream>
#include <list>
using namespace std;
int main() {
int n, m;
cout << "请输入小孩人数n: ";
cin >> n;
cout << "请输入数到第m个小孩出列: ";
cin >> m;
list<int> childList; // 利用STL的list容器来模拟小孩围成一圈
for (int i = 1; i <= n; i++) {
childList.push_back(i);
}
// 迭代器指向第一个小孩,开始数数
auto iter = childList.begin();
while (childList.size() > 1) {
// 数m个小孩,不断循环列表
for (int i = 1; i < m; i++) {
iter++;
if (iter == childList.end()) { // 判断是否已经到列表尾部
iter = childList.begin();
}
}
// 输出出列小孩的编号
cout << "第" << *iter << "个小孩出列" << endl;
// 删掉出列小孩的节点
iter = childList.erase(iter);
// 如果已经到列表尾部,需要将迭代器重新指向开头
if (iter == childList.end()) {
iter = childList.begin();
}
}
// 输出剩下的小孩
cout << "胜利者是第" << *childList.begin() << "个小孩" << endl;
return 0;
}