title: Java remove duplicates from linked list
body: <p>I want to remove duplicates from sorted linked list {0 1 2 2 3 3 4 5}. </p>
  
  <p>`</p>
  
  <pre><code>public Node removeDuplicates(Node header)
  {
      Node tempHeader = null;
      if(header != null) 
          tempHeader = header.next;
      else return header;
      Node prev = header;
      if((tempHeader == null)) return header ;
  
      while(tempHeader != null)
      {
          if(tempHeader.data != prev.data)
          {
              prev.setNext(tempHeader);
          }
      tempHeader = tempHeader.next;
      }
      prev = header;
      printList(prev);
      return tempHeader;
  }
  </code></pre>
  
  <p>`</p>
  
  <p>prev.setNext(tempHeader) is not working correctly inside the while loop. Ideally when prev = 2 and tempHeader = 3, prev.next should be node with data = 3.</p>
  
  <p>Printlist function just takes header pointer and prints the list.</p>
  
  <p>Node definition is given below.</p>
  
  <pre><code>public class Node
  {
      int data;
      Node next;
  
      public Node getNext() {
          return next;
      }
      public void setNext(Node next) {
          this.next = next;
      }
  }
  </code></pre>