Lets assume root=[7,3,3,1,2,3,4,5]
and a call
root->next = removeKFromList( root->next, 3 );
That should result: root=[7,1,2,4,5] ?
You have created the nodes somehow. Was it with
new
? If yes, then you have to
delete
.
Smart pointers would be a smart thing to use; saves errors.
Anyway, you do have two cases to consider:
1. The first node on list has k. Take it out.
2. It does not. Skip it.
Every node on the list is the first node of the rest of the list.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
|
// remove the prefix matches
while ( l and l->value == k ) {
auto dead = l;
l = l->next;
delete dead;
}
// handle the internal
if ( l ) {
auto tmp = l;
// skip
while ( tmp->next and tmp->next->value != k ) {
tmp = tmp->next;
}
tmp->next = removeKFromList( tmp->next, k );
}
return l;
|
If that code is correct, then we start with l=[3,3,1,2,3,4,5]
There will be two to erase and after them l=[1,2,3,4,5]
Therefore tmp=[1,2,3,4,5] and the skip progresses to tmp=[2,3,4,5]
Then we resort to recursion, although iteration would be just fine.
The second call starts with l2=[3,4,5]
Again, the erasure produces l2=[4,5] and skip until tmp2=[5]
The third call starts with l=[] and that is what it returns. The second call thus returns the [4,5]
to the first call that appends that to the [1,2] producing [1,2,4,5]
Now we are ready to return, and our caller will have their root=[7,1,2,4,5].