前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >数据结构--链表--约瑟夫环问题(单向循环链表)

数据结构--链表--约瑟夫环问题(单向循环链表)

作者头像
Michael阿明
发布2021-02-20 10:24:24
2890
发布2021-02-20 10:24:24
举报

问题:一群人站成一个圆圈,从一个人开始报数,1, 2 ,。。。m,报到m的拉出去砍了,求被砍的顺序和最后一个活下来的。

利用单向循环链表实现

C++代码如下:(参考书籍:数据结构与算法实验指导书)

代码语言:javascript
复制
#include <iostream>
using namespace std;

struct NodeType
{
    int num;
    char name[20];
    NodeType* next;
};
class Jose
{
private:
    NodeType* p_head;
public:
    Jose()
    {
        p_head = new NodeType;  //带空头的链表
        p_head->next = p_head;  //空的循环链表
    }
    ~Jose(){}
    void creat();
    void print();
};
void Jose::creat()
{
    int i = 0, n;
    NodeType *newp, *tempNode;
    tempNode = p_head;
    cout << "\n enter total nums of people: ";
    cin >> n;
    for(i = 0; i < n; ++i)
    {
        newp = new NodeType;
        newp->num = i+1;
        cout << "\n enter name: ";
        cin >> newp->name;
        newp->next = p_head;    //此处p_head为尾部哨兵
        tempNode->next = newp;   //不断地往尾部(尾部哨兵之前)插入节点
        tempNode = newp;
    }
    tempNode->next = p_head->next;  //断开空头哨兵
    delete p_head;                  //释放哨兵节点
    p_head = tempNode->next;        //头结点指向第一个节点
}
void Jose::print()
{
    int m,i;
    NodeType *del = p_head, *tempNode;
    cout << "\n enter value m(m>=2):";
    cin >> m;
    cout << "\n start:" << endl;
    while(del->next != del)         //链表节点个数不为1
    {
        for(i = 1; i < m; ++i)        //del往后移动m位
        {
            tempNode = del;
            del = del->next;
        }
        cout << del->num << " " << del->name << endl;
        tempNode->next = del->next;     //断开del节点
        delete del;                     //释放del节点
        del = tempNode->next;
    }
    cout << del->num << " " << del->name << endl;
    delete del;             //链表只剩一个节点直接删除
}

int main()
{
    Jose gameList;
    gameList.creat();
    gameList.print();
    cout << "press any key to exit!" ;
    cin.get();
    return 0;
}

Valgrind检查结果:

假设有5个人,报数3的出列,手动模拟如下

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2019-03-14 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • C++代码如下:(参考书籍:数据结构与算法实验指导书)
  • Valgrind检查结果:
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档