Remove duplicates from a sorted linked list.
Example 1:
Input:
11->11->11->21->43->43->60
Output: 11->21->43->60.
Example 2:
Input: 11->11->11->11->21->43->43->60
Output: 11->21->43->60.
1. class Node-:
It defines a class Node to represent the nodes of the linked list. Each node contains an integer data and a
pointer next to the next node.
2. remove Duplicates function:-
The removeDuplicates function is used to remove duplicates from the sorted linked list. It takes the head of
the linked list as an argument.
3. Inside the removeDuplicates function:-
It starts with a pointer current initialized to the head of the list and a pointer next_next to store the
next pointer of a node to be deleted.
If the list is empty (i.e., current is NULL), it does nothing and returns.
It then traverses the list using a while loop until the end of the list is reached.
Within the loop, it compares the data of the current node with the data of the next node. If they are equal,
it proceeds to remove the duplicate:
It stores the next pointer of the node to be deleted in next_next.
It frees the memory of the next node using free.
It updates the next pointer of the current node to point to next_next.
If the data of the current node and the next node are not equal, it simply advances the current pointer to
the next node.
The push function is a utility function used to insert a new node at the beginning of the linked list. It
takes a reference to the head of the linked list and the data for the new node as arguments.
The printList function is a utility function used to print the elements of the linked list.
4. In the main function:-
It creates an empty linked list head.
It uses the push function to insert elements into the linked list in sorted order.
It prints the original linked list before removing duplicates.
It calls the removeDuplicates function to remove duplicates.
It prints the modified linked list after removing duplicates.