0

Trying to delete a particular element from a linked list

void delete(int num) {
        Node node = head;
        Node prev = null;
        if(head.data == num) {
            head = head.next;
        }
        while(node.next!=null) {
            prev= node;
            if(node.next.data==num) {
                node.next=node.next.next;
                node=prev;
            }
            node= node.next;
        }
        if(node.data == num) {
            prev.next = null;
        }
    }

error

    java.lang.NullPointerException
at hackerEarth.linkedList.delete(linkedList.java:44)
at hackerEarth.linkedList.main(linkedList.java:67)

line 44 is - while(node.next!=null) line 67 is - delete(sc.nextInt());

2 Answers2

0

you are just checking for node.next and not checking node itself

node.next != null

Just take a look - below you are assigning

node.next = node.next.next;

no let us imagine that after this node.next is null - few lines beneath we have

node = node.next;

what does mean that now node is null what causes NPE in the line 44

while(node.next != null) // NPE! trying to access 'next' of null
m.antkowicz
  • 11,566
  • 12
  • 33
0

Here's the fixed function:

void delete(int num) {
        Node node = head;
        Node dummy = new Node();//Creating a dummy starting node.
        Node prev = dummy;
        prev.next = node;

        while(node!=null) {
            if(node.data==num)
            {
                prev.next = node.next;//Removing current node.
                node.next = null;//Removing reference to the next node.
                break;//Exiting the loop
            }
            prev = node;
            node = node.next;
        }
        dummy = null;
    }

Imagine the nodes to be boxes with one pointer to the next box. You have to make the previous node point to the next node, so that the current node is skipped. This removes the attachment to the previous node. Then you have to remove the attachment from the current node to the next node, so that it is not connected to the linked list in any way. This means that it is not used anywhere in the code, so Java automatically deletes it from memory to save space.

the_ritz
  • 282
  • 1
  • 14
  • Why would a `delete` method allocate new memory? It's better to write a few more lines of code with `if` statements. – Andreas Aug 31 '19 at 16:32
  • @Andreas The method won't allocate new memory, but it's generally a good habit to get rid of all connections if you're deleting from a linked list. – the_ritz Aug 31 '19 at 17:26
  • `new Node()` is allocation of new memory. I didn't say whether it was temporary or more persistent, but it certainly *is* allocation of new memory. --- Not sure what you mean by *"generally a good habit to get rid of all connections"*. Of course you *have to* get rid of all references to the node being removed. I just suggested that you should use `if` statements to accomplish that, not new memory. – Andreas Aug 31 '19 at 17:30