简体   繁体   中英

Error adding element first in linked list java

I trying to add a Parson in Doubly linked list. 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. 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 . You can try the following for addFirst method.

public void addFirst(Node z){

    if(head == null) {
       head = z;
       tail = z;
    } else {
       z.setNext(head);
       head.setPrevioue(z);
    }
    size++;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM