约瑟夫问题循环链表c++
时间: 2023-11-08 21:05:08 浏览: 94
C++循环链表之约瑟夫环的实现方法
好的,关于约瑟夫问题循环链表的C++实现,可以参考以下代码:
```c++
#include <iostream>
using namespace std;
struct Node {
int val;
Node* next;
Node(int x) : val(x), next(NULL) {}
};
int josephus(int n, int m) {
Node* head = new Node(1);
Node* cur = head;
for (int i = 2; i <= n; i++) {
cur->next = new Node(i);
cur = cur->next;
}
cur->next = head;
while (cur != cur->next) {
for (int i = 1; i < m; i++) {
cur = cur->next;
}
Node* tmp = cur->next;
cur->next = tmp->next;
delete tmp;
}
int res = cur->val;
delete cur;
return res;
}
int main() {
int n = 5, m = 3;
cout << josephus(n, m) << endl; // 输出3
return 0;
}
```
阅读全文