title: Inserting Node in a Sorted linked list
body: <p><img src="https://i.stack.imgur.com/rUt5q.png" alt="enter image description here"></p>
  
  <p>The following code ensures that elements are inserted in a linked list in a sorted manner.</p>
  
  <p>After understanding the logic behind this i decided to test it on my own. However when i wrote my version of the code it as follows. </p>
  
  <pre><code>  public class SortedList {
  
      private Node first;
  
      public SortedList() {
          first = null;
      }
  
      public boolean isEmpty() {
          return first == null;
      }
  
      public void insert(int j) {
          Node newNode = new Node(j);
          Node previous = null;
          Node current = first;
  
          while (current != null &amp;&amp; j &gt; current.iData) {
              previous = current;
              current = current.next;
          }
  
          if (previous == null)
              first = newNode;
  
          else
  
              newNode.next = current;
          previous.next = newNode;
  
      }
  
      public Node remove() {
          Node temp = first;
          first = first.next;
          return temp;
      }
  
      public void displayList() {
          System.out.println("First to -----&gt; Last");
          Node current = first;
  
          while (current != null) {
              current.display();
              current = current.next;
          }
      }
  
  }
  </code></pre>
  
  <p><strong>NODE CLASS</strong></p>
  
  <pre><code>public class Node {
  
      public int iData;
      public Node next;
  
      public Node(int id) {
          iData = id;
      }
  
      public void display() {
          System.out.println(iData + " ");
      }
  
  }
  </code></pre>
  
  <p><strong>TEST CLASS</strong></p>
  
  <pre><code>public class SortedListApp {
  
      public static void main(String[] args) {
  
          SortedList list = new SortedList();
  
          list.insert(20);
          list.insert(40);
  
          list.displayList();
  
          list.insert(10);
          list.insert(30);
          list.insert(50);
  
          list.displayList();
  
          list.remove();
  
          list.displayList();
  
      }
  
  }
  </code></pre>
  
  <p>The only difference between the two is that in my version when the while loop terminates. I first set the next value of the newNode to the current and then i set the next value of previous to the new Node. In the original code posted they have it reversed. For some reason this throws Null Pointer Exception. I am wondering why?</p>
  
  <p>From what i understand, once the new node finds its place for insertion. We have reference to the previous node and the current node and we are trying to insert the new node in the middle of the previous and the current. Therefore what i do is set the next of the new Node to the current and then i set the next of previous node to the new node.</p>
  
  <p>Please tell me where i am wrong.</p>