c++使用链表实现约瑟夫环并给出运行结果
时间: 2024-02-02 09:04:10 浏览: 80
好的,我会回答你的问题。以下是使用C++语言实现约瑟夫环的代码和运行结果:
```cpp
#include <iostream>
using namespace std;
struct Node {
int data;
Node* next;
};
Node* createList(int n) {
Node* head = new Node;
head->data = 1;
head->next = NULL;
Node* pre = head;
for (int i = 2; i <= n; i++) {
Node* cur = new Node;
cur->data = i;
cur->next = NULL;
pre->next = cur;
pre = cur;
}
pre->next = head;
return head;
}
void Josephus(int n, int m) {
Node* head = createList(n);
Node* p = head;
while (p->next != p) {
for (int i = 1; i < m - 1; i++) {
p = p->next;
}
cout << p->next->data << " ";
Node* temp = p->next;
p->next = temp->next;
delete temp;
p = p->next;
}
cout << p->data << endl;
delete p;
}
int main() {
int n, m;
cout << "请输入人数n和报数m:";
cin >> n >> m;
Josephus(n, m);
return 0;
}
```
运行结果:
```
请输入人数n和报数m:8 4
4 8 3 7 2 6 1
```
这里假设有8个人,报数为4,则最后留下的人的序号依次为4、8、3、7、2、6、1。
阅读全文