class Node{
String data;
Node next;
public Node(){}
public Node(String data, Node next) {
this.data = data;
this.next = next;
}
}
public class List {
private Node head;
private int size=0;
public List(){
head = new Node(null,null);
}
public void add(String data){
Node temp=head;
while(temp!=null){
temp=temp.next;
}
[color=red]temp.next = new Node(data,null);[/color] //哪错了?
}
public int getSize(){
return size;
}
public void getNode(int i){
Node temp = head;
for(int n=0;n<0;n++){
if(temp!=null)
temp=temp.next;
}
System.out.println(" "+temp.data);
}
public void print(){
for(Node temp=head.next; temp!=null; temp=temp.next){
System.out.println(" "+temp.data);
}
}
public static void main(String[] args){
List l = new List();
l.add("a");
l.add("b");
l.add("c");
l.add("d");
l.print();
l.getNode(2);
}
}
我只是解决了你的Null异常,靠的是 更改程序的流程。
而你的这个链表设计有问题。
你的Add方法,没有对head进行操作。head的data是null 但是head的next节点不是null
所以 你可以添加,但是在getNode时,一次也没有调用temp.next.
最后 还是head节点。所以输入的是head的data, 当然null了
[code="java"]
public void add(String data){
Node temp=head;
while(temp!=null){
temp=temp.next;
}
// 跳出循环式 temp 已经为null了
// 调用下一句,当然报错了
temp.next = new Node(data,null);
} [/code]
[color=blue][b]
改成这样试试:[/b][/color]
[code="java"]
Node temp = head;
if (head.next != null) {
do {
temp = temp.next;
} while (temp.next != null);
}
temp.next = new Node(data,null);
[/code]