slash89mf
slash89mf

Reputation: 1067

Remove elements from list with recursion c++

I have this function that should delete elements that are multiple of input number.

ptr_lista rmv_mul(ptr_list p,int n){

    if(p==NULL){
      return(p);
    }

    if (p->val%n==0){
        ptr_list tmp;             
        tmp = p->next;
        delete(p);
        rmv_mul(p->next,n);
        return (p);
    }
    else{
        rmv_mul(p->next,n);
        return (p);
    }
}

Executing this on a list from 0 to 10, the problem is that elements are deleted but are not null, so my print function gives me this:

0 28992848 28992816 28992784 28992752 28992720 28992688 28992656 28992624 28992592

How can i solve this problem?

Upvotes: 1

Views: 772

Answers (2)

6502
6502

Reputation: 114521

Without even trying to follow your logic these two lines already show you've a problem:

delete(p);
rmv_mul(p->next,n);

the reason is that after delete p (no parenthesis needed, btw) you are not allowed to access p->next (it's undefined behavior).

Upvotes: 1

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726619

The problem is that your code ignores the return value of rmv_mul, even though that's the new list pointer. Instead of returning p in the first branch, your code should be returning whatever is returned by rmv_mul:

ptr_lista rmv_mul(ptr_list p,int n){
    if(p==NULL){
      return(p);
    }
    if (p->val%n==0){
        ptr_list tmp = p->next;
        delete(p);
        return rmv_mul(tmp, n); // <<== Pass tmp, not p; p is deleted
    } else {
        p->next = rmv_mul(p->next, n); // <<== Assign to p->next
        return (p);
    }
}

Upvotes: 0

Related Questions