使用C++分文件编写链表和结构体解决约瑟夫问题
时间: 2024-03-07 08:48:31 浏览: 69
好的,以下是使用C++分文件编写链表和结构体解决约瑟夫问题的示例代码:
首先是链表的头文件 List.h:
```
#ifndef LIST_H
#define LIST_H
#include <iostream>
struct Node {
int data;
Node* next;
};
class List {
public:
List();
~List();
void addNode(int data);
void deleteNode(Node* node);
void printList();
Node* getHead();
private:
Node* head;
Node* tail;
};
#endif
```
链表的实现文件List.cpp:
```
#include "List.h"
List::List() {
head = nullptr;
tail = nullptr;
}
List::~List() {
Node* current = head;
while (current != nullptr) {
Node* next = current->next;
delete current;
current = next;
}
}
void List::addNode(int data) {
Node* node = new Node;
node->data = data;
node->next = nullptr;
if (head == nullptr) {
head = node;
tail = node;
} else {
tail->next = node;
tail = node;
}
}
void List::deleteNode(Node* node) {
if (node == head) {
head = head->next;
} else {
Node* current = head;
while (current->next != node) {
current = current->next;
}
current->next = node->next;
if (node == tail) {
tail = current;
}
}
delete node;
}
void List::printList() {
Node* current = head;
while (current != nullptr) {
std::cout << current->data << " ";
current = current->next;
}
std::cout << std::endl;
}
Node* List::getHead() {
return head;
}
```
接下来是解决约瑟夫问题的主文件main.cpp:
```
#include <iostream>
#include "List.h"
int main() {
int n, k, m;
std::cout << "请输入总人数n:";
std::cin >> n;
std::cout << "请输入起始位置k:";
std::cin >> k;
std::cout << "请输入报数上限m:";
std::cin >> m;
List list;
for (int i = 1; i <= n; i++) {
list.addNode(i);
}
Node* current = list.getHead();
for (int i = 1; i < k; i++) {
current = current->next;
}
while (n > 1) {
for (int i = 1; i < m; i++) {
current = current->next;
}
Node* next = current->next;
list.deleteNode(current);
current = next;
n--;
}
std::cout << "剩下的人的编号是:" << current->data << std::endl;
return 0;
}
```
以上代码实现了一个能够解决约瑟夫问题的程序。在这个程序中,List类表示链表,Node结构体表示链表中的节点。主程序中先读入约瑟夫问题的相关参数,然后创建一个包含n个节点的链表。接下来,程序按照约瑟夫问题的规则遍历链表,并删除指定的节点,直到只剩下一个节点为止。最后输出剩下的节点的编号。
阅读全文