把约瑟夫环改成 下一次循环用出圈人的密码(不是现在这样,用下一个人的密码),按单链表建立、单链表个性化密码修改、改成循环链表、算法执行并输出这几个模块化封装。c++代码
时间: 2024-10-25 15:16:50 浏览: 17
在C++中,我们可以将约瑟夫环(Josephus Problem)的解决方案拆分成几个模块来实现。下面是一个简化的示例,我们将它封装成几个部分:
1. **链表结构** (LinkedList.h)
```cpp
#ifndef LINKED_LIST_H
#define LINKED_LIST_H
class Node {
public:
int value;
Node* next;
explicit Node(int val = 0) : value(val), next(nullptr) {}
};
class LinkedList {
private:
Node* head;
public:
LinkedList() : head(nullptr) {}
// 添加节点到链表尾部
void addNode(int value) {
if (!head) {
head = new Node(value);
} else {
Node* current = head;
while (current->next) {
current = current->next;
}
current->next = new Node(value);
}
}
// 获取链表长度
int length() const {
int count = 0;
Node* temp = head;
while (temp) {
++count;
temp = temp->next;
}
return count;
}
// 根据值删除节点
void removeNodeWithValue(int value) {
if (head && head->value == value) {
head = head->next;
} else {
Node* prev = nullptr;
Node* current = head;
while (current && current->value != value) {
prev = current;
current = current->next;
}
if (current) {
prev->next = current->next;
}
}
}
};
#endif // LINKED_LIST_H
```
2. **约瑟夫环核心算法** (JosephusProblem.cpp)
```cpp
#include "LinkedList.h"
int josephusProblem(int n, int k) {
LinkedList list;
for (int i = 1; i <= n; ++i) {
list.addNode(i);
}
Node* current = list.head;
while (list.length() > 1) {
int nextIndex = (k - 1 + list.length()) % list.length();
list.removeNodeWithValue(current->value);
current = current->next;
}
return current ? current->value : 0; // 返回最后一个存活者
}
```
3. **主函数** (main.cpp)
```cpp
#include "LinkedList.h"
#include <iostream>
int main() {
int n = 10; // 环中人数
int k = 4; // 删除间隔
std::cout << "The last surviving number is: " << josephusProblem(n, k) << std::endl;
return 0;
}
```
阅读全文