约瑟夫问题Java解决
2011-05-20 15:18
393 查看
思路是建立链表,还有种方法是用数组,稍后写好后在公布。 下面的代码我在韩顺平老师代码的基础上,加入了一个lastChild的引用,但程序的运行结果有误,现在还没解决,稍后解决了在发布。。 package pfl.losthandkerchief_new; public class LostHandkerchief_new { public static void main(String[] args) { // 创建链接对象 CycLink cycLink = new CycLink(); // 设置人的总数 cycLink.setLen(6); // 创建链表 cycLink.creatLink(); // 设置从第K个人开始数数 cycLink.setK(2); // 设置往下数m下 cycLink.setM(2); // 打印出链表 cycLink.show(); // 打印出最后一个人的号码 cycLink.play(); } } class Child { int no;// 人的号码 Child nextChild = null;// 下一个人的引用 Child lastChild = null;// 上一个人的引用 // Child finalChild = null;//最后一个人的引用 public Child(int no) { this.no = no; } } class CycLink { // 定义第一个人的引用 Child firstChild = null; // 定义一个中间变量,用来将每个人连接起来 Child temp = null; // 人的总个数 int len = 0; // 定义从第几个人开始数数 int k = 0; // 定义开始往下数的个数 int m = 0; // 定义一个过度量 Child ch = null; // 提供外界设置人的总个数 public void setLen(int len) { this.len = len; } // 提供外界设置从第几个人开始数数 public void setK(int k) { this.k = k; } // 提供外界设置开始往下数的人数 public void setM(int m) { this.m = m; } // 创建链表 public void creatLink() { for (int i = 1; i <= len; i++) { if (i == 1) { // 创建第一个人 Child child = new Child(i); this.temp = child; this.ch = child; this.firstChild = child; } else { if (i == len) { Child child = new Child(i); temp.nextChild = child; this.temp = child; temp.lastChild = ch; this.ch = child; temp.nextChild = this.firstChild; this.firstChild.lastChild = child; } else { Child child = new Child(i); temp.nextChild = child; this.temp = child; temp.lastChild = ch; this.ch = child; } } } } public void play() { // 1.找到开始数数的人 // 定义第一个人 Child temp = this.firstChild; for (int i = 1; i < k; i++) { temp = temp.nextChild; } while (this.len != 1) { // 2.往下数m下 for (int i = 1; i < m; i++) { temp = temp.nextChild; } // 3.将数到的那个人清楚圈 temp.lastChild.nextChild = temp.nextChild; temp = temp.nextChild; this.len--; } // 4.打印出最后一个人的号码 System.out.println(temp.no); } //打印出链表 public void show() { // 定义一个跑龙套 Child temp = this.firstChild; do { System.out.println(temp.no); temp = temp.nextChild; } while (temp != this.firstChild); } }
相关文章推荐
- 约瑟夫问题 java解法(双向链表解决)
- 用java解决约瑟夫问题
- 约瑟夫问题(Josephus)java链表解决
- 韩顺平老师的JAVA教学视频:解决约瑟夫问题
- java 数组 解决 约瑟夫问题 算法
- java数组解决约瑟夫(Josephus)问题
- Java解决约瑟夫问题代码实例
- java-----五子棋小游戏(四)-----解决闪烁问题(双缓冲)
- 解决在java的ssm框架中使用ajax提交数据遇到的跨域问题
- 第99课:使用Spark Streaming+Kafka实战对论坛网站动态行为的多维度分析及java.lang.NoClassDefFoundError问题解决完整内幕版本解密
- java 乱码问题解决九步曲
- java环境变量设置和问题及解决方法
- weblogic java.lang.OutOfMemoryError: PermGen space 问题解决方法
- eclipse及Java常用问题及解决办法汇总
- 无法删除Java(TM) Platform SE binary打开问题解决(修改jar中的文件)
- 解决java中中文传值出现乱码问题
- 解决Java中int不能为空而Oracle数据库中Number可以的问题
- Linux 下Tomcat运行一段时间报java.net.SocketException: Too many open files的错误问题解决
- 初学JAVA,一段网络通信小代码的问题解决
- java 中解决中文乱码问题的方法