#include <iostream>
using namespace std;

typedef struct Lnode{
    int data;
    struct Lnode *next; 
}LNode,*Linklist;

void creatlist(Linklist &head, int n){
    head = new LNode;
    head->next = NULL;
    LNode *r = head;
    for(int i = 1; i <= n; i++){
        LNode *p = new LNode;
        p->data = i;
        p->next = NULL;
        r->next = p;
        r = p;
    }
    r->next = head->next;
}

void josephus(Linklist &head, int n, int m){
    LNode *p = head->next;
    LNode *q;
    int num = 0;
    while(num < n){
        for(int i = 1; i < m; i++){
            q = p;
            p = p->next;
        }
        cout << p->data << ' '; //输出
        q->next = p->next;
        LNode *newNode = new LNode;
        newNode->data = p->data;
        newNode->next = head->next;
        head->next = newNode;
        delete p;
        p = q->next;
        num++;
    }
}

int main(){
    int n, m;
    cout << '请输入玩游戏的人数M,回车输入:';
    cin >> n;
    Linklist head = NULL;
    creatlist(head, n);
    int numPasswords;
    cout << '请输入每遍游戏的报数密码次数,回车输入:';
    cin >> numPasswords;
    for(int i = 0; i < numPasswords; i++){
        cout << '请输入第' << i+1 << '遍游戏的报数密码,回车输入:';
        cin >> m;
        josephus(head, n, m);
        cout << endl;
    }
    return 0;
}

这段代码实现了使用循环链表解决约瑟夫问题,并可以进行多轮游戏。

主要功能:

  • creatlist 函数:创建一个包含 n 个节点的循环链表,节点数据从 1 到 n。
  • josephus 函数:模拟约瑟夫游戏,输出每轮出列的人员编号,并将出列人员加入到新队列的头部,保持出列顺序。
  • main 函数:接收用户输入的游戏人数和每轮游戏的报数密码,并进行多轮游戏模拟,输出每轮游戏的结果。

代码解读:

  1. josephus 函数中,使用两个指针 pq 遍历链表,p 指向当前报数的人,q 指向 p 的前一个节点。
  2. 每轮游戏循环报数 m 次,找到要出列的节点 p
  3. q->next 指向 p->next,删除节点 p
  4. 创建一个新的节点 newNode,将 p 的数据复制到 newNode 中。
  5. newNode 插入到新队列的头部。
  6. p 指向 q->next,继续下一轮游戏。

使用方法:

  1. 编译并运行代码。
  2. 按照提示输入玩游戏的人数。
  3. 按照提示输入每轮游戏的报数密码次数。
  4. 按照提示输入每轮游戏的报数密码。
  5. 程序将输出每轮游戏的结果,即出列人员的编号。

示例:

输入:

玩游戏的人数M:5
每遍游戏的报数密码次数:2
第1遍游戏的报数密码:2
第2遍游戏的报数密码:3

输出:

2 4 1 5 3 
1 3 5 4 2 

注意:

  • 代码中使用了 cout 进行输出,你需要包含头文件 iostream
  • 代码中使用了动态内存分配,你需要在程序结束时手动释放内存,避免内存泄漏。
C++数据结构:循环链表实现约瑟夫问题,多轮游戏及出列顺序

原文地址: https://www.cveoy.top/t/topic/Rux 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录