title: Deleting duplicates a linked lists Java
body: <p>I am trying to implement a method that deletes all the duplicates from a linked list. I've managed to take care of the tail. In other words, if the tail's <code>data</code> was a duplicate, the program wouldn't throw an <code>exception error</code>. Now, I'm trying to take care of the head such that if the <code>head</code>'s data is a duplicate, I want to set the <code>head</code> = <code>head.next</code> so that the duplicate is no longer in the linked list. However my method <code>deleteDuplicates</code> does not handle the <code>head</code>. Anybody have suggestions to fix this problem?</p>
  
  <pre><code>class Node {
          private Node next = null; 
          private int data; 
  
          public Node(int d) {
              data = d; 
          }
  
          void appendToTail(int d) {
              Node end = new Node(d); 
              Node n = this; 
  
              while(n.next != null) {
                  n = n.next; 
              }
              n.next = end; 
          }
  
          void print() {
              Node n = this; 
              while(n != null) {
                  System.out.println(n.data); 
                  n = n.next; 
              }
          }
  
          Node deleteDuplicates(Node head, int d) {
              Node n = head;
              if(n.data == d) {
                  head = head.next; 
                  n = n.next; 
              }
              while(n != null) {
                  if(n.next.data == d) {
                      if(n.next == null &amp;&amp; n.next.data == d) {
                          return head;
                      }
                      n.next = n.next.next;
                  }
                  n = n.next; 
              }
              return head; 
          }
  
          public static void main(String [] args) {
              Node x = new Node(9); 
              x.appendToTail(5);
              x.appendToTail(9);
              x.appendToTail(6);
              x.appendToTail(9);  
              x.appendToTail(7);
              x.appendToTail(9);  
              x.appendToTail(8); 
              x.appendToTail(9); 
              x.deleteDuplicates(x, 9); 
              x.print(); 
          }   
      }
  </code></pre>