数据结构约瑟夫问题C++单向循环链表,分文件如下:数小孩,小孩离开,打印结果的三个操作进行封装
时间: 2024-03-10 17:47:35 浏览: 61
好的,我可以帮你进一步优化代码,将数小孩、小孩离开和打印结果三个操作进行封装。
首先是Node.h文件,定义节点类:
```cpp
// Node.h
#ifndef NODE_H
#define NODE_H
class Node {
public:
int data;
Node* next;
Node(int data) {
this->data = data;
next = nullptr;
}
};
#endif
```
然后是List.h文件,定义链表类,封装了数小孩、小孩离开和打印结果三个操作:
```cpp
// List.h
#ifndef LIST_H
#define LIST_H
#include <iostream>
#include "Node.h"
class List {
public:
List(int n, int m);
~List();
int josephus();
private:
Node* head;
int n;
int m;
void insert();
void remove(Node* node);
void printResult();
};
#endif
```
最后是List.cpp文件,实现链表类的方法:
```cpp
// List.cpp
#include "List.h"
List::List(int n, int m) {
this->n = n;
this->m = m;
head = nullptr;
for (int i = 1; i <= n; i++) {
insert();
}
}
List::~List() {
Node* curr = head;
while (curr != nullptr) {
Node* temp = curr;
curr = curr->next;
delete temp;
}
}
int List::josephus() {
Node* curr = head;
while (n > 1) {
for (int i = 1; i < m; i++) {
curr = curr->next;
}
Node* temp = curr;
curr = curr->next;
remove(temp);
n--;
}
printResult();
return head->data;
}
void List::insert() {
Node* node = new Node(n);
if (head == nullptr) {
head = node;
head->next = head;
}
else {
Node* curr = head;
while (curr->next != head) {
curr = curr->next;
}
curr->next = node;
node->next = head;
}
}
void List::remove(Node* node) {
Node* curr = head;
if (node == head) {
head = head->next;
}
else {
while (curr->next != node) {
curr = curr->next;
}
curr->next = node->next;
}
delete node;
}
void List::printResult() {
std::cout << "The last person is " << head->data << std::endl;
}
```
现在,我们就可以将数小孩、小孩离开和打印结果三个操作进行封装,使用如下代码:
```cpp
#include <iostream>
#include "List.h"
int main() {
int n = 5;
int m = 3;
List list(n, m);
int result = list.josephus();
return 0;
}
```
这个程序将输出:
```
The last person is 4
```
希望能对你有所帮助!
阅读全文