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.
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 2List = [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 2sList = [3]-[5]-null
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With