Remove duplicates from a sorted linked list | Java program for the above approach ; Function to insert a node at the beginging of the linked * list ; allocate node ; put in the data ; link the old list off the new node ; move the head to point to the new node ; Function to print nodes in a given linked list ; Function to remove duplicates ; Driver Code ; Created linked list will be 11 -> 11 -> 11 -> 13 -> 13 -> 20
import java . io . * ; import java . util . * ; class Node { int data ; Node next ; Node ( ) { data = 0 ; next = null ; } } class GFG { static Node push ( Node head_ref , int new_data ) { Node new_node = new Node ( ) ; new_node . data = new_data ; new_node . next = ( head_ref ) ; head_ref = new_node ; return head_ref ; } static void printList ( Node node ) { while ( node != null ) { System . out . print ( node . data + " ▁ " ) ; node = node . next ; } } static void removeDuplicates ( Node head ) { HashMap < Integer , Boolean > track = new HashMap < > ( ) ; Node temp = head ; while ( temp != null ) { if ( ! track . containsKey ( temp . data ) ) { System . out . print ( temp . data + " ▁ " ) ; } track . put ( temp . data , true ) ; temp = temp . next ; } } public static void main ( String [ ] args ) { Node head = null ; head = push ( head , 20 ) ; head = push ( head , 13 ) ; head = push ( head , 13 ) ; head = push ( head , 11 ) ; head = push ( head , 11 ) ; head = push ( head , 11 ) ; System . out . print ( " Linked ▁ list ▁ before ▁ duplicate ▁ removal ▁ " ) ; printList ( head ) ; System . out . print ( " Linked list after duplicate removal "); removeDuplicates ( head ) ; } }