c++编写约瑟夫环全部代码
时间: 2024-01-12 09:14:48 浏览: 84
好的,下面是完整的C++代码实现:
```cpp
#include <iostream>
using namespace std;
class Node {
public:
int value;
Node* next;
Node(int val) : value(val), next(nullptr) {}
};
int josephus_circle(int n, int m) {
// create a circular linked list
Node* head = new Node(1);
Node* curr = head;
for (int i = 2; i <= n; i++) {
Node* node = new Node(i);
curr->next = node;
curr = node;
}
curr->next = head;
// start counting and removing nodes
curr = head;
while (curr->next != curr) {
for (int i = 1; i < m - 1; i++) {
curr = curr->next;
}
Node* temp = curr->next;
curr->next = curr->next->next;
delete temp;
curr = curr->next;
}
int result = curr->value;
delete curr;
return result;
}
int main() {
int n = 10;
int m = 3;
int result = josephus_circle(n, m);
cout << "The last person standing is " << result << endl;
return 0;
}
```
在该代码中,我们定义了一个Node类来表示链表中的一个节点,然后实现了josephus_circle函数来解决约瑟夫环问题。最后在main函数中调用josephus_circle函数,并输出最后剩下的人的编号。
运行该代码,输出结果为:
```
The last person standing is 4
```
这表示在10个人围成一圈、每报到第3个人就删除的情况下,最后剩下的人的编号为4。
阅读全文