zoukankan      html  css  js  c++  java
  • 暑假自学(4)

    今天是小学期的最后一天题目是约瑟夫问题的求解,代码如下:
    #include<iostream>
    using namespace std;
    typedef struct node
    {
        int data;
        struct node* next;
    };
    node* create()
    {
        int n;
        node* head, * p1, * p2;
        cout << "请输入人数:" << endl;
        cin >> n;
        if ( n < 1)
        {
            exit(0);
        }
        else
        {
            head = new node;
      if(head==NULL)exit(0);
      head->data=1;
            head->next = NULL;
            p1 = head;
            for (int i=2;i <= n;i++)
            {
                p2 = new node;
                p1->next = p2;
                p1 = p1->next; 
       p1->data=i;
            }
            p1->next = head;
        }
        return head;
    }
    void findAndKillK(node* head, int stratId, int m)
    {
        node* p1;
        p1 = head;
        node* p2 = head;
        while (p2->data != stratId)
        {
            p1 = p2;
            p2 = p2->next;
        }
        while (p2->next != p2)
        {
            for (int i = 1; i < m; i++)
            {
                p1 = p2;
                p2 = p2->next;
            }
            p1->next = p2->next;
    cout << "出列的人的id是:";
            cout << p2->data << endl;
            free(p2);
            p2 = p1->next;
        }
        cout << "出列的人的id是:";
        cout << p2->data << endl;
        free(p2);
    }
    int main()
    {
        node* head = create();
        cout << "请输入stratId:" << endl;
        int stratId;
        cin >> stratId;
        cout << "数到m的人出列:" << endl;
        int m;
        cin >> m;
        findAndKillK(head, stratId, m);
        return 0;
    }

  • 相关阅读:
    docker 安装mysql5.7 加my.cnf
    docker安装redis 配置文件
    私库nexus 配置
    mysql 多个字段建立唯一索引
    scm 一些记录
    tomcat 线程数、NIO配置、内存配置
    为什么简单的一个select查询都要加上事务控制
    powerdeginer report layout
    powerdesigner-连接mysql
    [转载]如何让自己变得有趣
  • 原文地址:https://www.cnblogs.com/buxiang-Christina/p/13276378.html
Copyright © 2011-2022 走看看