Given a sorted linked list, delete all nodes that have duplicate numbers (all occurrences), leaving only numbers that appear once in the original list.
Examples:
Input: 23->28->28->35->49->49->53->53
Output: 23->35
Input: 11->11->11->11->75->75
Output: empty List
Note that this is different from Remove Duplicates From Linked List
The idea is to maintain a pointer (prev) to the node which just previous to the block of nodes we are checking for duplicates. In the first example, the pointer prev would point to 23 while we check for duplicates for node 28. Once we reach the last duplicate node with value 28 (name it current pointer), we can make the next field of prev node to be the next of current and update current=current.next. This would delete the block of nodes with value 28 which has duplicates.
Javascript
<script>
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( " List is empty" );
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(
"Before removal of duplicates<br/>" );
printList();
removeAllDuplicates();
document.write(
"<br/>After removal of duplicates<br/>" );
printList();
</script>
|
Output:
List before removal of duplicates
23 28 28 35 49 49 53 53
List after removal of duplicates
23 35
Time Complexity: O(n)
Please refer complete article on Remove all occurrences of duplicates from a sorted Linked List for more details!