假定一个数m,从第k个小孩起,顺时针方向数,每数到第m个小孩时,该小孩离开。请分别使用c++数组和链表的方式完成全部代码
时间: 2024-03-06 08:50:13 浏览: 18
使用 C++ 数组的方式:
```c++
#include <iostream>
using namespace std;
void josephus_array(int n, int k, int m) {
int children[n];
for (int i = 0; i < n; i++) {
children[i] = i + 1;
}
int index = k - 1;
while (n > 0) {
index = (index + m - 1) % n;
cout << "第" << k << "个小孩离开,编号为" << children[index] << endl;
for (int i = index; i < n - 1; i++) {
children[i] = children[i+1];
}
n--;
if (n == 0) {
break;
}
k = (k + m - 2) % n + 1;
}
}
int main() {
josephus_array(10, 3, 4);
return 0;
}
```
使用 C++ 链表的方式:
```c++
#include <iostream>
using namespace std;
class Node {
public:
int val;
Node* next;
Node(int v) : val(v), next(NULL) {}
};
void josephus_linked_list(int n, int k, 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;
Node* pre = NULL;
cur = head;
while (cur->next != cur) {
for (int i = 1; i < m; i++) {
pre = cur;
cur = cur->next;
}
cout << "第" << k << "个小孩离开,编号为" << cur->val << endl;
pre->next = cur->next;
delete cur;
cur = pre->next;
k = cur->val;
}
cout << "最后一个小孩编号为" << cur->val << endl;
delete cur;
}
int main() {
josephus_linked_list(10, 3, 4);
return 0;
}
```
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)