Remove Duplicates from Sorted List
PROBLEM :
Given a sorted linked list, delete all duplicates such that each element appear only once.
For example,
Given 1->1->2, return 1->2.
Given 1->1->2->3->3, return 1->2->3.
--------------------------------------------------------------------------------
SIMPLE c++ IMPLEMENTATION :
--------------------------------------------------------------------------------
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct ListNode* deleteDuplicates(struct ListNode* head) {
struct ListNode *ptr ,*temp ;
if(head==NULL)
return ;
temp=head ;
while(temp->next!=NULL)
{
if(temp->val==temp->next->val)
{
ptr=temp->next ;
temp->next=ptr->next ;
free(ptr) ;
}
else
temp=temp->next ;
}
return head ;
}
---------------------------------------------------------------------------------
Given a sorted linked list, delete all duplicates such that each element appear only once.
For example,
Given 1->1->2, return 1->2.
Given 1->1->2->3->3, return 1->2->3.
--------------------------------------------------------------------------------
SIMPLE c++ IMPLEMENTATION :
--------------------------------------------------------------------------------
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct ListNode* deleteDuplicates(struct ListNode* head) {
struct ListNode *ptr ,*temp ;
if(head==NULL)
return ;
temp=head ;
while(temp->next!=NULL)
{
if(temp->val==temp->next->val)
{
ptr=temp->next ;
temp->next=ptr->next ;
free(ptr) ;
}
else
temp=temp->next ;
}
return head ;
}
---------------------------------------------------------------------------------
Comments
Post a Comment