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;
    }
    这段代码是我在了解链表的相关知识后所出来的,当然,这也让我发现了很多问题,例如头结点和头指针的概念不清楚或者不了解head的定义,不过最后我也总算是搞明白了,不枉我费了许多时间和精力。在完成了这十个代码之后,明天我就要写程序报告了,今天完成了第一个程序的报告,明天争取做完剩下的报告,最后成这一系列的任务之后,我就要开始正式的学习java了,明天的作业大概就是争取写完报告。
    总的来说今天的收获很多,明日继续努力,争取早日写完作业。

  • 相关阅读:
    微软小娜APP的案例分析
    嵌入式第12次实验
    嵌入式第11次实验
    嵌入式第10次实验报告
    嵌入式第9次实验
    软工 小组作业(第二次)
    嵌入式软件设计第8次实验报告-140201236-沈樟伟
    5月17下
    5月17上
    5月15上午
  • 原文地址:https://www.cnblogs.com/L-L-ALICE/p/13276310.html
Copyright © 2011-2022 走看看