约瑟夫问题求解!!
public class Test1 {
public static void main(String[] args) {
Cyclink cyclink = new Cyclink();
cyclink.setlen(5);
cyclink.setk(2);
cyclink.setm(2);
cyclink.creatlink();
cyclink.show();
cyclink.play();
}
}
class Child {
int no;
Child nextChild;
public Child(int no) {
this.no = no;
}
}
class Cyclink {
Child temp = null;
Child firstChild = null;
int len;
int k=0 ;
int m=0;
//private Child ;
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 play() {
Child temp=this.firstChild;
while(this.len!=1){
// 找到第K个shu
for (int i = 1; i < k; i++)
{
temp=temp.nextChild;
} //从第K个开始数m次
for(int j=1;j<m;j++)
{
temp=temp.nextChild;
}
Child temp2=temp;
while(temp2.nextChild!=temp)
{
temp2=temp2.nextChild;
}
temp2.nextChild=temp.nextChild;
temp=temp.nextChild;
this.len--;
}
System.out.println("抛出的"+temp.no);
}
public void creatlink() {
for (int i = 1; i <=len; i++) {
if (i == 1) {
Child ch = new Child(i);
this.firstChild = ch;
this.temp = ch;
}
if (i == len) {
Child ch = new Child(i);
temp.nextChild = ch;
temp = firstChild;
} else {
Child ch = new Child(i);
temp.nextChild = ch;
temp = ch;
}
}
}
public void show() {
Child temp;
temp=this.firstChild;
do {
System.out.println(temp.no);
temp=temp.nextChild;
} while (temp!=this.firstChild);
}
}
我写的代码
运行后的结果如下:
Exception in thread "main" java.lang.NullPointerException
at Cyclink.show(Test1.java:101)
at Test1.main(Test1.java:10)
1
1
2
3
4
5
我的问题是:
1.为什么编译没有出错 但是一运行就直接报出异常?
2.还有我的paly()函数好像没有运行啊这是什么原因?
求高手帮忙解答下 小弟不胜感激!!!
[最优解释]
逻辑有错误,所以出异常了,因为出了一场所以play()没有执行到。逻辑错误如下:
public void creatlink() {
for (int i = 1; i <=len; i++) {
if (i == 1) {
Child ch = new Child(i);
this.firstChild = ch;
this.temp = ch;
}
if (i == len) {
Child ch = new Child(i);
temp.nextChild = ch;//第四个的下一个是第五个
ch.nextChild = firstChild;//第五个的下一个是第一个
//temp = firstChild;
} else {
Child ch = new Child(i);
temp.nextChild = ch;
temp = ch;
}
}
}
[其他解释]
问题在楼主的if if else结构。
当i==1时,创建了一个Child对象。创建完后,去判断if(i==len),这时不等。进入下面的else, 这时,i=1,就又创建了一个Child(1). 所以输出两个1。
改正方法,把中间的if 改成else if 即可。
[其他解释]
嗯嗯 对了 这下没有报错了
不过为什么我的show()函数怎么重复打了个第一个子节点的编号1呢?
Child temp;
temp=this.firstChild;
do {
System.out.println(temp.no);
temp=temp.nextChild;
} while (temp!=this.firstChild);
}//这里应该只把编号1打一次才对啊 怎么连续重复输出了2个 1?
[其他解释]
--------------------------------------------
好的 谢谢 get it!
还有楼上的那位大哥 也谢谢啦!