约瑟夫环c++循环链表代码
时间: 2023-11-26 07:48:30 浏览: 104
以下是C++实现循环链表中约瑟夫环的代码:
```cpp
#include <iostream>
using namespace std;
typedef struct Node {
int data;
struct Node* next;
} Node, *LinkList;
// 初始化循环链表
void init(LinkList& L, int n) {
LinkList p = new Node;
L = new Node;
p->data = 1;
L = p;
for (int i = 1; i < n; i++) {
LinkList q = new Node;
q->data = i + 1;
p->next = q;
p = q;
}
p->next = L; // 让链表的最后一个元素指向头结点构成循环链表
}
// 约瑟夫环
void josephus(LinkList& L, int k, int m) {
LinkList p = L, q = L;
while (p->next != p) {
for (int i = 1; i < k; i++) {
q = p;
p = p->next;
}
for (int i = 1; i < m; i++) {
q = p;
p = p->next;
}
q->next = p->next;
cout << p->data << " ";
delete p;
p = q->next;
}
cout << p->data << endl;
}
int main() {
int n, k, m;
cout << "请输入总人数n、起始报数k、出圈数字m:" << endl;
cin >> n >> k >> m;
LinkList L;
init(L, n);
josephus(L, k, m);
return 0;
}
```
阅读全文