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 ;
}

---------------------------------------------------------------------------------

Comments

Popular posts from this blog

Count ways to N'th Stair(Order does not matter)

Replace all ‘0’ with ‘5’ in an input Integer

Chocolate Distribution Problem

Remove characters from the first string which are present in the second string

Primality Test ( CodeChef Problem code: PRB01 )