class Node1 {
int a;
Node1 next;
}
public class Mylist {
Node1 head=null;
public static void main(String args[])
{
Mylist b=new Mylist();
int i=1;
while(i<=15)
{b.insert(i);i++;}
b.showlist();
}
Node1 gettop()
{
return head;
}
void insert(int obj)
{
Node1 temp=null;
if(this.head==null)
{ head=new Node1();
temp=new Node1();
temp.a=obj;
temp.next=null;
head.next=temp;
}
else
{
temp=new Node1();
temp.a=obj;
temp.next=this.head.next;
this.head.next=temp;
}
}
void showlist()
{
Node1 ptr=null;
ptr=this.head;
if(ptr==null)
{System.out.println("NULL");}
while(ptr!=null)
{ ptr=ptr.next;
System.out.print(ptr.a+" ");
}
}
}
以上是一个链式堆栈的代码,运行能得到预期的结果,但是结果出现之后ECLIPSE会转到DEBUG模式,并且报空指针错误.这我就不明白了,如果我用了未实例化的指针,那怎么又会运行出指针所指向的正确结果呢?运行结果如下:
java.lang.NullPointerException
at Mylist.showlist(Mylist.java:48)
at Mylist.main(Mylist.java:14)
15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 Exception in thread "main"
那些数字是把链表堆栈中的数据倒序打印出来所得到的,和预期相符合,就是这几个异常不知道怎么回事;