丢手帕问题

来源:互联网 发布:如何年薪百万程序员 编辑:程序博客网 时间:2024/04/28 23:14

package Task;/** *  * @author 链表解决丢手帕问题(约瑟夫问题) *  */public class CycLink { public static void main(String args[]) {  CycLinkModel cycLink = new CycLinkModel();  cycLink.setLen(5);  cycLink.creatLink();  cycLink.setK(2); // 从第几个起  cycLink.setM(2); // 中间隔几个  cycLink.play(); // 开始  //cycLink.show(); }}/* * 设置链表 --JAVA用引用做链表-- */class Child { int no; // 存放数据 Child nextChild = null;  // 构造方法给no赋值 public Child(int no) {  this.no = no; } // 得到no public int getNo() {  return no; }}// 环形链表class CycLinkModel { // 先定义一个指向链表的第一个小孩的引用 // 指向第一个小孩的引用,不能动 Child firstChild = null; // 定义一个跑龙套的,不停的把链表连接起来 Child temp = null; // 定义一个只想跑龙套的前一个 Child tempfront = null; // 设置属性 int len = 0; // 表示有几个小孩; int k = 0; // 表示从第几个开始数 int m = 0; // 表示中间隔几个数 // 连接链表 public void creatLink() {  for (int i = 1; i <= len; i++) {   Child ch = new Child(i);   if (i == 1) {    this.firstChild = ch;    this.temp = ch;   } else if (i == len) {    temp.nextChild = ch;    temp = ch;    temp.nextChild = firstChild;   } else {    temp.nextChild = ch;    temp = ch;   }  } } // 设置方法去访问属性 // 设置m,隔几个 public void setM(int m) {  this.m = m; } // 设置len,链表大小 public void setLen(int len) {  this.len = len; } // 设置k,从第几个数 public void setK(int k) {  this.k = k; } // 开始play public void play() {  temp = this.firstChild;  tempfront = temp;  // 1.先找到开始数数的人k  for (int i = 1; i < k; i++) {   tempfront = temp;   temp = temp.nextChild;  }  while (this.len != 1) {   // 2.数m下,找打第m个   for (int i = 1; i < m; i++) {    // 记录temp前一个位置    tempfront = temp;    // 找到第m个    temp = temp.nextChild;   }   // 3.将第数到的m小孩删除,推出圈   System.out.print(temp.getNo() + " ");   //跳过删除的孩子,指向删除孩子的下一个   tempfront.nextChild = temp.nextChild;   //删除之后从下一位开始   temp = temp.nextChild;   this.len--;  }  //最后一个孩子  System.out.print(temp.getNo()); } // 显示循环链表 public void show() {  // 跑龙套  temp = this.firstChild;  do {   for (int i = 1; i <= len; i++) {    System.out.print(temp.getNo() + " ");    temp = temp.nextChild;   }  } while (temp.nextChild == firstChild); }}

0 0
原创粉丝点击