Given a sorted linked list (elements are sorted in ascending order). Eliminate duplicates from the given LL, such that output LL contains only unique elements.
Input format: Linked list elements (separated by space and terminated by 1)
Sample Input 1 :
1 2 3 3 3 4 4 5 5 5 7 -1
Sample Output 1 :
1 2 3 4 5 7
Description:
In this question, we are given a sorted linked list with duplicate elements in it. Our task is to remove the duplicate nodes of the linked list. Since the list is sorted, the duplicate elements will be present in consecutive orders, that makes the work a lot easier.
Example:
Lets the list be:
1->2->3->3->4->4->4->NULL
The modified list will be:
1->2->3->4->NULL
To solve this problem, we keep the temp pointer pointing to node. While(temp -> next != NULL), we check if the data of temp is equal to data of temp->next. If they are equal, we will point the temp-> next to temp -> next ->next.
Original LL: 3-> 3-> 4-> ...
After Change: 3-> 4-> ... Leaving out the middle 3->
This will keep on until we reached the end of the list and return head at the end.
Steps
1. 1->2->3->3->4->4->4->NULL, temp = 1 2. 1->2->3->3->4->4->4->NULL, temp = 2 3. 1->2->3->3->4->4->4->NULL, temp = 3 4. 1->2->3->4->4->4->NULL, temp = 4 5. 1->2->3->4->4->NULL, temp = 4 Finally, 1->2->3->4->NULLFunction:
Node *removeDuplicate(Node* head){ //temp pointing to head Node *temp = head; while(temp->next != NULL && temp != NULL){ //Duplicate Found if(temp->data == temp->next->data){ //DUplicate Removed temp -> next = temp ->next ->next; } else{ //No Duplicate Present temp = temp->next; } } //Return Head return head; }C++ Code:
Output