#include <iostream>
#include <fstream>
#include <string>
using namespace std;
// 定义结构体
typedef struct Node
{
int data;
Node* next;
} LNode,*LinkList;
// 创建一个空的循环链表
Node* createList(int n)
{
Node* head = new Node();
head->data = 1;
Node* prev = head;
for (int i = 2; i <= n; i++)
{
Node* newNode = new Node();
newNode->data = i;
prev->next = newNode;
prev = newNode;
}
prev->next = head; // 形成环
cout<<"成功创建链表"<<endl;
return head;
}
// 创建一个单向循环链表并读取文件
/*void CreateList(Node* &L,const std::string& filename)
{
std::ifstream file(filename);
L=new Node;
L->next=NULL;
L = nullptr; // 初始化链表为空
Node* tail = nullptr; // 用于跟踪链表的尾部
int value;
// 读取文件并创建链表
while (file >> value)
{
}
file.close();
}
}*/
//删除相应的节点
void ListDelete(Node*& current)
{
Node* temp = current;
current = current->next;
delete temp;
}
void Next(Node*& current)
{
current = current->next;
}
//查询某人的信息
void getCharacter()
{
}
//打印所有人的信息
void PrintCharacter(int n)
{
int current;
for(int j=0; j <= n; j++)
{
}
cout<<"现在总人数为"<<current;
}
void Josephus(int n, int m)
{
Node* head = createList(n); // 创建环形链表
Node* current = head;
for (int i = 0; i < n - 1; i++)
{
for (int j = 0; j < m - 1; j++)
{
Next(current);
}
cout << "出列的人是: " << current->next->data << endl;
ListDelete(current->next);
cout<<"现在总人数为"<<n-i<<endl;
}
cout << "最后留下的人是: " << current->data << endl;
}
int main()
{
int n, m;
cout << "请输入总人数n和报数间隔m: ";
cin >> n >> m;
cout<<"总人数"<<n<<",报数间隔"<<m<<endl;
//PrintCharacter();
Josephus(n, m);
return 0;
}
自用备份ing
最新推荐文章于 2024-10-31 20:10:41 发布