Remove all occurrences of duplicates from a sorted Linked List | class to create Linked lIst ; Function to insert data nodes into the Linked List at the front ; Function to remove all occurrences of duplicate elements ; Create a dummy node that acts like a fake head of list pointing to the original head ; Dummy node points to the original head ; Until the current and previous values are same , keep updating current ; If current has unique value i . e current is not updated , Move the prev pointer to next node ; When current is updated to the last duplicate value of that segment , make prev the next of current ; Update original head to the next of dummy node ; Function to print the list elements ; Driver code
var head = null ; class Node { constructor ( val ) { this . val = val ; this . next = null ; } } function insert ( data ) { var new_node = new Node ( data ) ; new_node . next = head ; head = new_node ; } function removeAllDuplicates ( ) { var dummy = new Node ( 0 ) ; dummy . next = head ; var prev = dummy ; var current = head ; while ( current != null ) { while ( current . next != null && prev . next . val == current . next . val ) current = current . next ; if ( prev . next == current ) prev = prev . next ; else prev . next = current . next ; current = current . next ; } head = dummy . next ; } function printList ( ) { var trav = head ; if ( head == null ) document . write ( " " ) ; while ( trav != null ) { document . write ( trav . val + " " ) ; trav = trav . next ; } } insert ( 53 ) ; insert ( 53 ) ; insert ( 49 ) ; insert ( 49 ) ; insert ( 35 ) ; insert ( 28 ) ; insert ( 28 ) ; insert ( 23 ) ; document . write ( " " ) ; printList ( ) ; removeAllDuplicates ( ) ; document . write ( " " ) ; printList ( ) ;