zoukankan      html  css  js  c++  java
  • 使用单向循环链表实现约瑟夫问题

    使用单向循环链表实现约瑟夫问题

    //Jose.cpp----使用单向循环链表实现约瑟夫问题
    //问题描述:n个人手拉手排成一个环,从第一个人开始数,每数到第m个人,第m个人出列,从下一人重新计数重新数,求全部出列后他们的出列顺序 
    #include <iostream.h>
    struct jose
    {
     int data;
     int no;
     struct jose * next;
    };

    int main()
    {
     struct jose *head,*p_curent,*p_find;
     int n,m;
     cout << "Please enter the total of numbers (n):";
     cin >> n;
     cout << "Please enter the counter number (m):";
     cin >> m;
     
     //初始化链表
     head=p_curent=new jose;//标记首表元地址,即头指针
     head->no=1;
     cout << "Please enter the first number :";
     cin >>head->data;
     //形成其余的n-1表元
     cout << "Please enter last numbers :"<<endl;
     for (int i=2;i<=n;i++)
     {
      p_curent->next=new jose;
      p_curent=p_curent->next;
      cin >> p_curent->data;
      p_curent->no=i;
     }//end for
     p_curent->next=head;//尾指针指向头指针,形成环,到这完成初始化链表

     //开始查询,第M个人出列,并输出
     cout << "Now : The  numbers of who will quit the cycle in turn are:"<<endl;
     while (n)//全部出列后结束循环
     {
      //掠过m-1个表元
      for (int j=1;j<m;j++)
       p_curent=p_curent->next;//end for
      //找到第M个人
      p_find=p_curent->next;
      //从表中删除第m个人,并输出第m个人
      p_curent->next=p_find->next;
      cout << p_find->data<<endl;
      //释放第m个表元占用的空间
      delete p_find;
      n--;
     }
     //end while
     
     return 0;
    }

    转载于 http://www.cppblog.com/jeonchen/articles/7070.html

  • 相关阅读:
    今日SGU 5.27
    今日SGU 5.26
    今日SGU 5.25
    软件工程总结作业
    个人作业——软件产品案例分析
    个人技术博客(α)
    结对作业二
    软工实践 二
    软工实践 一
    《面向对象程序设计》六 GUI
  • 原文地址:https://www.cnblogs.com/zhuzhudexiaoshijie/p/3329269.html
Copyright © 2011-2022 走看看