java泛型问题

sevendays 2015-03-08 01:47:48
用链表去实现了一个简单的stack结构,但是发现用泛型的过程中会出现空指针异常,不是太明白为什么,希望大家能帮忙看看。代码如下:
这是链表部分,错误出现在class Node<T>,这里空指针异常

public class LinkedList<T> {
private Node<T> head;



public LinkedList(){
head=null;

}

public void insertNode(T value){
if(head==null){
head.data=value;
head.next=null;
}

Node<T> node=new Node<T>(value);
node.next=head;
head=node;
}


public T remove(){
Node<T> temp=head;
head=head.next;
return temp.data;
}

public boolean isEmpty(){
return (head==null);
}



class Node<T>{
private T data;
private Node<T> next;

public Node(){
data=null;
next=null;
}

public Node(T value){
data=value;
next=null;
}

public void changeData(T value){
data=value;
}

}

}


这是stack部分:

public class Stack_LinkedList<T> {
private LinkedList<T> stack;

public Stack_LinkedList(){
stack=new LinkedList<T>();
}

public void push(T value){
stack.insertNode(value);
}

public T pop(){
return stack.remove();
}

public boolean isEmpty(){
return stack.isEmpty();
}

}

class test7{
public static void main(String[] args){
Stack_LinkedList<Integer> stack=new Stack_LinkedList<Integer>();

for(int i=0;i<100;i++){
stack.push(i);
}

System.out.println();
while (!stack.isEmpty()){
System.out.print(stack.pop()+" ");
}

System.out.println();
}
}
...全文
128 1 打赏 收藏 转发到动态 举报
写回复
用AI写文章
1 条回复
切换为时间正序
请发表友善的回复…
发表回复
爱摸鱼de老邪 2015-03-08
  • 打赏
  • 举报
回复
错在第一个LinkedList类中的insertNode方法,应该改为: public void insertNode(T value) { if (head == null) { head = new Node<T>(value); } Node<T> node = new Node<T>(value); node.next = head; head = node; } head为null,怎么能够进行其他操作呢。

62,614

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧