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

  • 相关阅读:
    HPU--1189 Ou à
    实数向整数的强制转换
    HPU--1166 阶乘问题(一)
    HPU--1163 大数A+B
    阿斯伯格综合征完全指南各章链接
    思维改变生活第10章、有效沟通
    Mathematica(MMA)闪电入门系列 目录与说明
    第二语言习得理论介绍
    第二语言习得实践方法
    复赛注意事项:关于文件读写的格式
  • 原文地址:https://www.cnblogs.com/zhuzhudexiaoshijie/p/3329269.html
Copyright © 2011-2022 走看看