一个关于链表的问题

一个关于链表的问题

问题描述:

怎么样可以在不定义结点类和链表类的情况下,创建一个链表,并且功能。下面是我自己做的一个实例,可是有问题,求帮解决。
public class Student
{
public int num;
public String name;
public int score;
public Student next;
public Student(int nu,String na,int sc,Student next)
{
this.num=nu;
this.name=na;
this.score=sc;
this.next=next;
}
public void SetNext(Student t)
{
this.next=t;
}
public Student GetNext()
{
return next;
}
public void find(int i)
{
Student t=null;
if(i10)
{
System.out.println("超出范围,位置非法!");
}
for(int j=0;j<i;j++)
{
t=t.GetNext();
}
System.out.println("学号为"+i+"的学生成绩为:"+t.score);
}
}
public class Search1 {

/**

  • @param args */ public static void main(String[] args) { // TODO Auto-generated method stub Student stu=new Student(0," ",0,null); for(int i=0;i<10;i++) { stu.SetNext(new Student(i+1,"stu"+i,(int)(Math.random()*100),stu)); stu=stu.GetNext(); } stu.find(3); }

}
但是,运行的时候提示find()方法里的t=t.GetNext()引用了空值,
Exception in thread "main" java.lang.NullPointerException
at MyTestPack.Student.find(Student.java:33)
希望朋友们能帮解决一下,,

你没有把链表的头引用记下来, 还有就是楼上的t赋值的问题, 我改了两个地方
public class Student {
public int num;
public String name;
public int score;
public Student next;

public Student(int nu, String na, int sc, Student next) {
    this.num = nu;
    this.name = na;
    this.score = sc;
    this.next = next;
}

public void SetNext(Student t) {
    this.next = t;
}

public Student GetNext() {
    return next;
}

public void find(int i) {
    Student t = this; //t要初值
    if (i < 1 | i > 10) {
        System.out.println("超出范围,位置非法!");
    }
    for (int j = 0; j < i; j++) {
        t = t.GetNext();
    }
    System.out.println("学号为" + i + "的学生成绩为:" + t.score);
}

public static void main(String[] args) {
    // TODO Auto-generated method stub
    Student stu = new Student(0, " ", 0, null);
    Student head = stu; //要记录链表的头
    for (int i = 0; i < 10; i++) {
        stu.SetNext(new Student(i + 1, "stu" + i, (int) (Math.random() * 100), stu));
        stu = stu.GetNext();
    }
    head.find(3); //要用头来找.
}

}

[code="java"]
Student t=null;
if(i10)
{
System.out.println("超出范围,位置非法!");
}
for(int j=0;j<i;j++)
{
t=t.GetNext();
}
[/code]
你的t 从头到脚也没有赋值,不空就不正常了。

t一开始就设置为null,getNext()肯定是null了