C++ 栈和队列 约瑟夫环
时间: 2023-12-12 10:03:59 浏览: 184
以下是C++中使用栈和队列解决约瑟夫环问题的例子:
使用栈:
```cpp
#include <iostream>
#include <stack>
using namespace std;
int main() {
int m, n;
cout << "请输入约瑟夫环的两个人数m和n:";
cin >> m >> n;
stack<int> s;
for (int i = m; i >= 1; i--) {
s.push(i);
}
int count = 1;
while (!s.empty()) {
int top = s.top();
s.pop();
if (count == n) {
cout << top << " ";
count = 1;
} else {
s.push(top);
count++;
}
}
return 0;
}
```
使用队列:
```cpp
#include <iostream>
#include <queue>
using namespace std;
int main() {
int m, n;
cout << "请输入约瑟夫环的两个人数m和n:";
cin >> m >> n;
queue<int> q;
for (int i = 1; i <= m; i++) {
q.push(i);
}
int count = 1;
while (!q.empty()) {
int front = q.front();
q.pop();
if (count == n) {
cout << front << " ";
count = 1;
} else {
q.push(front);
count++;
}
}
return 0;
}
```
阅读全文