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;
    }

  • 相关阅读:
    JS框架_(Bootstrap.js)实现简单的轮播图
    Unity3D_(网格导航)简单物体自动寻路
    Android_(菜单)选项菜单
    Android_(传感器)获取手机中的传感器
    Java基础__Java中常用数学类Math那些事
    Java基础__Java中异常处理那些事
    Android_(控件)动态添加或删除Spinner下拉菜单
    Android_(消息提示)多种使用Toast的消息提示
    Java基础__随机生成1~15之间不重复的数字
    Android_(自动化)获取手机存储卡的容量
  • 原文地址:https://www.cnblogs.com/buxiang-Christina/p/13276378.html
Copyright © 2011-2022 走看看