Recommand · October 22, 2021 0

Trying to create a method in singlylinkedlist to add before a specific number using java

Here is what I’ve made so far but whenever I try to run the program I get an error saying:

Exception in thread "main" java.lang.NullPointerException: Cannot read field "prev" because "<local3>" is null
  at addBeforeSinglyLinkedList.addBefore(addBeforeSinglyLinkedList.java:30)
  at addBeforeSinglyLinkedList.main(addBeforeSinglyLinkedList.java:51)

Code:

public class addBeforeSinglyLinkedList {
    Node head, tail;
    
    public addBeforeSinglyLinkedList() {
        head = tail = null;
    }

    public class Node {
        int data;
        Node prev;

        public Node(int data, Node prev) {
            this.data = data;
            this.prev = prev;
        }
    }

    public void addToHead(int data) {
        if (head==null) {
            head = tail = new Node(data, null);
        } else {
            head = new Node(data, head);
        }
    }

    public void addBefore(int targetValue, int data) {
        Node tmp;
        for (tmp=head; tmp!=null; tmp=tmp.prev) {}

        Node prevofTmp = tmp.prev;
        tmp.prev = new Node(data, prevofTmp);
    }

    public void showReverse() {
        for (Node tmp=head; tmp!=null; tmp=tmp.prev) {
            System.out.print("[" + tmp.data + "]");
        }
        System.out.println("");
    }

    public static void main(String[] args) {
        addBeforeSinglyLinkedList list1 = new addBeforeSinglyLinkedList();

        list1.addToHead(9);
        list1.addToHead(27);
        list1.addToHead(13);
        list1.addToHead(58);

        list1.showReverse();

        list1.addBefore(9, 7);
        list1.addBefore(27, 23);

        list1.showReverse();
    }
}

Nvm I managed to correct the method by doing this….

public void addBefore(int targetValue, int data) {
    Node tmp;
    for(tmp=head; tmp.data!=targetValue && tmp.prev!=null; tmp=tmp.prev) {}

        Node prevofTmp = tmp.prev;
        tmp.prev = new Node(data, prevofTmp);
}

public void showReverse() {
    for(Node tmp=head; tmp!=null; tmp=tmp.prev) {
        System.out.print("[" + tmp.data + "]");
    }
    System.out.println("");
}