Code using C language . The time is 8ms


  • 0
    B

    Add a NULL head

      struct ListNode* removeElements(struct ListNode* head, int val) {
        if(head==NULL)
            return NULL;
        struct ListNode* temp1=malloc(sizeof(struct ListNode));
        struct ListNode* temp2=malloc(sizeof(struct ListNode));
        temp1->next=head;
        temp2=temp1;
        while(temp2->next!=NULL)
        {
            if(temp2->next->val==val)
                temp2->next=temp2->next->next;
            else
                temp2=temp2->next;
        }
        return temp1->next;
    }

  • 0
    S

    when you return temp1->next , arent you returning a pointer to the last node in the linked list?


  • 0
    B

    temp1 is always the head of this list,it does not move.


  • 0
    P

    I did by this method can you please explain why it is showing an runtime error

    Last executed input:
    [1], 1
    but it worked in linux without any run time error.

    struct ListNode* removeElements(struct ListNode* head, int val) {

    struct ListNode *temp=head,*prv;
    
    if(!head)
    
    return NULL;
    if(head->val==val)
    head=head->next;
    while(temp){
        if(temp->next->val==val){
            prv=temp->next;
            temp->next=prv->next;
        }
        temp=temp->next;
    }
    return head;
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.