A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© 旭辉lin 中级黑马   /  2014-8-30 11:55  /  1062 人查看  /  0 人回复  /   1 人收藏 转载请遵从CC协议 禁止商业使用本文


  1. //数据结构 约瑟夫问题
  2. /*用java实现的丢手帕问题,即有n个人围成圈,从第k个人开始从1报数,
  3. 报到第m个人时出局,从出局人的下一个开始从新报数,
  4. 报到第m个人时出局......如此循环直至最后一人出局*/
  5. class Child {
  6. int no; //编号
  7. Child nextChileChild = null; //指向下一个人

  8. public Child(int no) {

  9. this.no = no;
  10. }

  11. }

  12. //链表类

  13. //环形链表
  14. class CycLink {

  15. //先定义一个指向链表第一个小孩的那个引用
  16. //指向第一个小孩的引用,不能动
  17. Child firstChild = null;
  18. Child temp = null;
  19. int len = 0;// 表示共有几个小孩
  20. int k;
  21. int m;

  22. //设置链表大小
  23. public void setLen(int len) {
  24. this.len = len;
  25. }

  26. public void setK(int k) {
  27. //设置第几个人开始数数
  28. this.k = k;
  29. }

  30. public void setM(int m) {
  31. //设置m
  32. this.m = m;
  33. }

  34. public void play() {
  35. //1找到开始数数的人
  36. Child temp = this.firstChild;
  37. for (int i = 1; i < k; i++) {
  38. temp = temp.nextChileChild;

  39. }
  40. //数M下
  41. while (this.len != 1) {
  42. for (int j = 1; j < m; j++) {
  43. temp = temp.nextChileChild;
  44. }
  45. Child temp2 = temp;// 找到要出圈的前一个小孩
  46. //讲数到M的小孩 退出圈
  47. temp2=temp2.nextChileChild;
  48. temp.nextChileChild=temp2.nextChileChild;
  49. System.out.println("现在出圈的是" + temp2.no);
  50. this.len--;
  51. }
  52. //打印最优一个小孩
  53. System.out.print("最后出圈的是:" + temp.no);
  54. }

  55. //初始化链表
  56. public void creatLink() {
  57. for (int i = 1; i <= len; i++) {

  58. if (i == 1) {
  59. //创建第一小孩
  60. Child child = new Child(i);
  61. this.firstChild = child;
  62. this.temp = child;
  63. } else {
  64. if (i == len) {
  65. Child child = new Child(i);
  66. temp.nextChileChild = child;
  67. temp = child;
  68. temp.nextChileChild = this.firstChild;

  69. } else {
  70. //继续创建小孩
  71. Child child = new Child(i);
  72. temp.nextChileChild = child;
  73. temp = child;
  74. }
  75. }

  76. }

  77. }

  78. public void show() {

  79. Child temChild = this.firstChild;
  80. do {
  81. System.out.println(temChild.no + "###");
  82. temChild = temChild.nextChileChild;
  83. } while (temChild != this.firstChild);
  84. }
  85. }

  86. //主方法类

  87. public class Demo4 {

  88. public static void main(String[] args) {
  89. //TODO Auto-generated method stub
  90. CycLink cyclink =new CycLink();
  91. cyclink.setLen(17);
  92. cyclink.creatLink();
  93. cyclink.setK(17);//17代表尾号//从1号开始念
  94. cyclink.setM(3);//输出念到3的人出圈
  95. cyclink.show();
  96. cyclink.play();
  97. }
  98. }

复制代码

0 个回复

您需要登录后才可以回帖 登录 | 加入黑马