您的位置:首页 > 编程语言 > Java开发

约瑟夫问题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);
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: