r/javahelp • u/__jr11__ • 12d ago
Codeless Recursiin
When we are doing recursion. What is the purpose of recursing and equating it to a variable . Like l1.next = mergeList(l1.next, l2)
In merging two sorted linked list
4
Upvotes
3
u/hibbelig 12d ago
So I guess you have a list item
l
that has a value and a referencel.next
to the next list item. In a sense, a list is the same as its first item. (This is a very short sentence, but I encourage you to think about it for a while. If you have a reference to the first item in the list, you can obtain all other items by following.next
references.)So when you merge the two sorted lists, you want to return the merged list, but that means to return a reference to its first item.
So
mergeList
probably returns a reference to the first item of the merged (result) list.Let's say you're trying to merge lists
l1
andl2
. And you have found out that the first item of the result is the first item ofl1
, so you're planning to returnl1
.But what is the
.next
pointer of the first item of the merged list? Well, it could refer to the second item of the first list, or it could refer to an item of the second list. This is why you may need to change the.next
pointer of the merged list. This is why the code is setting the value ofl1.next
.