我试图在Doubly链表中添加一个Parson。我写代码,我没有看到任何错误。但在运行中有错误。任何可以帮助我??
public class LinkedList{
Node head, tail;
int size;
public LinkedList()
{ head = null; tail = null; size = 0; }
public void addFirst(Node z){
Node w = head.getNext();
z.setNext(w);
z.setPrevioue(head);
w.setPrevioue(z);
head.setNext(z);
size = size+1;
}
public void Display()
{
System.out.println("Douply Linked List: " + size);
Node car = head;
while(car != null){
System.out.println(car.getNumber() + " <-> ");
car = car.getNext();
} }
主要:
public class DouplyLinkedList {
public static void main(String[] args) {
LinkedList dll = new LinkedList();
dll.addFirst(new Node(20, null, null));
dll.addFirst(new Node(90,null,null));
dll.Display();
答案 0 :(得分:0)
你没有检查head是否为null,如果是,你将得到零点异常。 试试这段代码:
public void addFirst(Node z){
if (head == null) {
head = z;
tail = z;
size = 1;
} else {
head.setPrevious(z);
z.setNext(head);
head = z;
size = size+1;
}
}
答案 1 :(得分:0)
最初头 null 。您可以尝试以下 addFirst 方法。
public void addFirst(Node z){
if(head == null) {
head = z;
tail = z;
} else {
z.setNext(head);
head.setPrevioue(z);
}
size++;
}