Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Recursively remove all occurrences of an item in a linked list

public static Node deleteAll(Node front, String target){
    if (front == null){ return null;}
    if (front.data.equals(target)){
        return deleteAll(front.next,target);
    }
    front.next=deleteAll(front.next,target);
    return front;
}

I'm trying to walk through this solution, but it is confusing me. Why doesn't it always result as null since at the end front will equal null.

like image 228
dogkid45 Avatar asked Oct 17 '22 22:10

dogkid45


1 Answers

When thinking about such problems it is a good idea to get a pen and paper and draw some stuff and think about it on a high level

For example
...............
Input
List: [3]-[2]-[5]-null
Target: 2
................

First call => Result

deleteAll(N[3], 2) => [3]
but next is now deleteAll(N[2], 2)
List = [3]-deleteAll(N[2], 2)

Second call

deleteAll(N[2], 2) => deleteAll(N[5], 2)
next node now skips the 2
List = [3]-deleteAll(N[5], 2)

Third call

deleteAll(N[5], 2) => [5]
but next is now deleteAll(null, 2)
List = [3]-[5]-deleteAll(null, 2)

Lat call returns null

List ends up clean with no 2s
List = [3]-[5]-null

like image 86
JoshKisb Avatar answered Oct 21 '22 01:10

JoshKisb