Remove Linked List Elements
PROBLEM :
Remove all elements from a linked list of integers that have value val.
Example
Given: 1 --> 2 --> 6 --> 3 --> 4 --> 5 --> 6, val = 6
Return: 1 --> 2 --> 3 --> 4 --> 5
--------------------------------------------------------------------------------
SIMPLE c++ IMPLEMENTATION :
--------------------------------------------------------------------------------
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct ListNode* removeElements(struct ListNode* head, int val) {
struct ListNode *temp,*ptr ;
if(head==NULL)
return head ;
while(head!=NULL&&head->val==val)
{
ptr=head ;
head=ptr->next ;
free(ptr) ;
}
if(head==NULL)
return head ;
temp=head ;
while(temp->next!=NULL)
{
if(temp->next->val==val)
{
ptr=temp->next ;
temp->next=ptr->next ;
free(ptr) ;
}
else
temp=temp->next ;
}
return head ;
}
---------------------------------------------------------------------------------
Remove all elements from a linked list of integers that have value val.
Example
Given: 1 --> 2 --> 6 --> 3 --> 4 --> 5 --> 6, val = 6
Return: 1 --> 2 --> 3 --> 4 --> 5
--------------------------------------------------------------------------------
SIMPLE c++ IMPLEMENTATION :
--------------------------------------------------------------------------------
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct ListNode* removeElements(struct ListNode* head, int val) {
struct ListNode *temp,*ptr ;
if(head==NULL)
return head ;
while(head!=NULL&&head->val==val)
{
ptr=head ;
head=ptr->next ;
free(ptr) ;
}
if(head==NULL)
return head ;
temp=head ;
while(temp->next!=NULL)
{
if(temp->next->val==val)
{
ptr=temp->next ;
temp->next=ptr->next ;
free(ptr) ;
}
else
temp=temp->next ;
}
return head ;
}
---------------------------------------------------------------------------------
Comments
Post a Comment