-1

I'm writing a method to remove duplicate Node, but it keeps getting NullPointerException at line: while (m.next != null).

public class Node {

    public int data;
    public Node next;

    public Node (int data) {
        this.data = data;
        this.next = null;
    }

    public void removeDup () {

        Node n = this;
        while (n != null) {
            Node m = n;

            while (m.next != null) {
                if (n.data == m.next.data) 
                    m.next = m.next.next;
                m = m.next;
            }

            n = n.next;
        }
    }
}
Filburt
  • 17,626
  • 12
  • 64
  • 115
  • Even if this wouldnt be yet another repetition of that basic problem "what is a NPE, and how do i fix it" ... we couldnt help here. Your input lacks a real [mcve], like: a bit of sample code that leads to the exception. Beyond that ... this loop looks good, the conditions should prevent a NPE. Finally: you have that method in the wrong class. A **Node** is just that: a node. Removing duplicates belongs onto some outer List class. And: consider to **not** make your fields public. You want to **hide** such internals, not announce them publicly. – GhostCat Jun 27 '19 at 08:22

2 Answers2

0

Consider the following 3 steps of your loop:

    while (m.next != null) { // 3. now in the next iteration, m == null, so you get 
                             //    NullPointerException
        if (n.data == m.next.data) 
            m.next = m.next.next; // 1. if m.next.next == null, you assign m.next = null
        m = m.next; // 2. then you assign m = null
    }
Eran
  • 387,369
  • 54
  • 702
  • 768
0

Can you please share the full code?

It looks like 'n' has not been instantiated and hence when you assign it to 'm', it is still NULL and hence the Exception.