7
回答
Exception in thread "main" java.lang.NullPointerException
利用AWS快速构建适用于生产的无服务器应用程序,免费试用12个月>>>   
/**
 * 功能:约瑟夫问题
 */
package com.sole;


public class Demo04{


/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
CycLink cyclink = new CycLink();

cyclink.setLen(5);
cyclink.createLink();
cyclink.showList();
}


}


class Child{
int num;
Child nextChild = null;

public Child( int num ){
this.num = num;
}
}


//环形链表
class CycLink{
//先定义一个指向链表第一个小孩的引用,不能动
Child firstChild = null;
Child temp = null;
int len = 0; //表示有几个小孩

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

//初始化环形链表
public void createLink(){
for(  int i =0; i<=len; i++ ){
if( i == 1 ){
//创建第一个小孩
Child ch = new Child( i );
this.firstChild = ch;
this.temp = ch;
}else {

if( i == len ){
Child ch = new Child( i );
temp.nextChild = ch;
temp = ch;
temp.nextChild = this.firstChild;
}else{
//继续创建小孩
Child ch = new Child( i );
temp.nextChild = ch;
temp = ch;
}
}
}
}


//打印环形链表
public void showList(){
Child temp = this.firstChild;
do{
System.out.println( temp.num );
temp = temp.nextChild;
}while( temp != this.firstChild );
}


}

总是出现这个错误,找不出来,请高手帮忙指点

举报
共有7个答案 最后回答: 5年前
//初始化环形链表 
public void createLink(){ 
for(  int i =0; i<=len; i++ ){ 
if( i == 1 ){ 
//创建第一个小孩 
Child ch = new Child( i ); 
this.firstChild = ch; 
this.temp = ch; 

}

黄底的地方应该是if(i==0)才是第一个,不然代码第一次就走的是else,temp当然是没有赋值,因为是null,所以会报异常

引用来自“妖魔舞”的答案

56行这temp.nextChild = ch;

temp为空啊,注意变量的作用范围

能不能说的具体点啊,怎么样给temp初始化???
public class Demo04 {
public static void main(String[] args) {
CycLink cyc = new CycLink();
cyc.setLen(5);
cyc.createLink();
cyc.showList();
}
}


class Child {
int num;
Child nextChild = null;


public Child(int num) {
this.num = num;
}
}


class CycLink {
Child firstChild = null;
Child temp = null;
int len = 0;


public void setLen(int len) {
this.len = len;
}


public void createLink() {
for (int i = 0; i <= len; i++) {
if (i == 0) {
Child ch = new Child(i);
this.firstChild = ch;
//temp.nextChild = ch;
this.temp = ch;
} else {
if (i == len) {
Child ch = new Child(i);
temp.nextChild = ch;
temp = ch;
temp.nextChild = this.firstChild;
} else {
Child ch = new Child(i);
temp.nextChild = ch;
temp = ch;


}
}
}
}

public void showList() {
temp = this.firstChild;
do {
System.out.println(temp.num);
temp = temp.nextChild;
} while(temp != this.firstChild);
}
}
这是经过编译运行没报错的!!!

顶部