• C++循环链表实现约瑟夫退圈(类封装)


    node.h

     1 #pragma once
     2 #include <iostream>
     3 #include <iomanip>
     4 using namespace std;
     5 
     6 struct number
     7 {
     8     int n;
     9     number *_next;
    10 };//结构体定义
    11 class node
    12 {
    13     int m,k;//m报数上限 k人数
    14     number *s;
    15 public://成员函数
    16     node(void);
    17     ~node(void);
    18     void Joseph();
    19     void set(int x);
    20     void Delete(int x);
    21 };

    node.cpp

     1 #include "node.h"
     2 node::node(void)
     3 {
     4     s=NULL;//构造函数 令指针s指向空
     5 }
     6 node::~node(void)
     7 {
     8 }
     9 void node::Joseph()
    10 {
    11     int i=0,l=0;
    12     cout<<"请输入总人数、报数上限:"<<endl;
    13     cin>>k>>m;
    14     cout<<"依次退圈的人:"<<endl;
    15     set(k);
    16     number *p=s,*q;
    17     while(l<k-1)
    18     {
    19         q=p;
    20         p=p->_next;
    21         i++;
    22         if(i==m)
    23         {
    24             l++;
    25             cout<<q->n<<""<<endl;//报数报到上限 记录退出成员号码
    26             Delete(q->n);//该成员退圈 及删除该节点
    27             i=0;
    28         }
    29     }
    30     cout<<"最后剩下的人: "<<s->n<<""<<endl;//最后链表中剩下的最后一个节点
    31 }
    32 void node::set(int x)//建立循环链表
    33 {
    34     int i;
    35     s=new number;
    36     s->n=1; s->_next=NULL;//没有设头结点
    37     number *p=s,*q=NULL;
    38     for(i=2;i<=x;i++)
    39     {
    40         q=new number;
    41         q->n=i;
    42         q->_next=NULL;
    43         p->_next=q;
    44         p=q;
    45     }
    46     p->_next=s;//最后一个节点指针指向第一个节点实现循环
    47 }
    48 void node::Delete(int x)//删除链表中数据为x的节点
    49 {
    50     number *p=s,*q=NULL;
    51     if(s->n==x)
    52     {
    53         while(p->_next!=s)
    54         {
    55             q=p;
    56             p=p->_next;
    57         }
    58         s=s->_next;
    59         p->_next=s;
    60     }
    61     else
    62     {
    63         while(p->n!=x)
    64         {
    65             q=p;
    66             p=p->_next;
    67         }
    68         q->_next=p->_next;
    69     }
    70 }

    main.cpp

    1 #include "node.h"
    2 void main()
    3 {
    4     node a;
    5     a.Joseph();
    6 }

    结果截图:

  • 相关阅读:
    VisualStudio2010配置OpenCV的一种一劳永逸的方法
    QT5 Failed to load platform plugin &quot;windows&quot; 终极解决方式 命令行问题
    轻松学习JavaScript二十二:DOM编程学习之节点操作
    Eclipse中安装TestNG插件
    Java Timer 定时器的使用
    技术开发团队的项目管理工具
    python里一个class可以定义多个构造函数
    python中的多继承
    python基础之使用os.system来执行系统命令
    python下划线变量的含义
  • 原文地址:https://www.cnblogs.com/yifengyifeng/p/5933931.html
Copyright © 2020-2023  润新知