Remove Duplicate Element from sorted Linked List Geeks For Geeks
class GfG
{
//Function to remove duplicates from sorted linked list.
Node removeDuplicates(Node head)
{
Node temp=head;
Node newNode;/*created in manner it wil help in reference adjustments*/
while(temp.next!=null){
int a=temp.data;
int b=temp.next.data;
if(a==b){
newNode=temp.next.next;
temp.next.next=null;
temp.next=newNode;
}
else{
temp=temp.next;
}
}
return head;
}
}
Approach:
Here we will take a node named temp which will point to the node head. This temp node will traverse till it reaches the last node at which temp.next==null. If we found duplicates then the reference of the middle node will be null and the previous node will point to the next node reference. In such a manner all duplicate nodes will be removed.
If no duplicates then iterations will be there in the forwarding direction.
TIME:O(N)[Geeks For Geeks Time: 1.4/3.1]
SPACE:O(1)[No data structure is used for storing any data]
Thanks for Reading.😇
Comments
Post a Comment