[英]Error adding element first in linked list java
I trying to add a Parson in Doubly linked list. 我试图在双重链接列表中添加一个Parson。 I write the code and I haven't seen any error.
我编写了代码,但没有看到任何错误。 But in a run there is error.
但是在运行中有错误。 Any on can help me??
有什么可以帮助我的吗?
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();
} }
the main: 主要的:
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();
youre not checking if head is null, if it is, you will get null point exception. 您不检查head是否为null,如果是,则将获得null点异常。 try this code :
试试这个代码:
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;
}
}
Initially head is null . 最初head为null 。 You can try the following for addFirst method.
您可以为addFirst方法尝试以下操作 。
public void addFirst(Node z){
if(head == null) {
head = z;
tail = z;
} else {
z.setNext(head);
head.setPrevioue(z);
}
size++;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.