GfG QA is closing soon... Please refer PRACTICE or GfG now on wards !!

Remove Linked List Elements

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

I have written code for the above mentioned problem, but it is showing runtime error, can anyone please point out the mistake?

Code that I wrote:-

class Solution {
public:
    ListNode* removeElements(ListNode* head, int val) {
        while(head->val==val)
        {
            ListNode *temp=head;
            head=head->next;
            delete temp;
        }
        ListNode *t=head,*prev=head;
        while(t!=NULL)
        {
           if(t->val==val)
           {
               ListNode *q=t; 
               prev->next=t->next;
               delete q;
               
           }
           else{
               prev=t;
           }
          
           t=t->next;
        }
        
        return head;
        
    }
};

asked Aug 2, 2016 by anonymous

1 Answer

this will help u

http://quiz.geeksforgeeks.org/linked-list-set-3-deleting-node/

 

void deleteNode(struct node **head_ref, int key)

{

    // Store head node

    struct node* temp = *head_ref, *prev;

 

    // If head node itself holds the key to be deleted

    if (temp != NULL && temp->data == key)

    {

        *head_ref = temp->next;   // Changed head

        free(temp);               // free old head

        return;

    }

 

    // Search for the key to be deleted, keep track of the

    // previous node as we need to change 'prev->next'

    while (temp != NULL && temp->data != key)

    {

        prev = temp;

        temp = temp->next;

    }

 

    // If key was not present in linked list

    if (temp == NULL) return;

 

    // Unlink the node from linked list

    prev->next = temp->next;

 

    free(temp);  // Free memory

}

answered Aug 2, 2016 by intakhab Ali
...