Easy C++ solution


  • 0
    Z

    class Solution {
    public:
    ListNode* removeElements(ListNode* head, int val) {
    ListNode *prev=new ListNode(0);
    prev->next=head;
    ListNode *p=prev;
    while(p&&p->next){
    if(p->next->val==val){
    p->next=p->next->next;
    }
    else p=p->next;
    }
    return prev->next;
    }
    };


  • 0
    S

    I had come up up with this solution and the OJ is showing "Runtime error". I just couldn't what is the problem with it, could you help me out?

    ...class Solution {
    public:
    ListNode* removeElements(ListNode* head, int val) {
    while(head->val==val)
    {
    ListNode *y;
    y=head;
    head=head->next;
    delete y;}

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

    };


  • 0
    B

    @shubhamverma2311 You should check if head was NULL before calling head->val.


Log in to reply
 

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