I'm trying to grasp the concept of Recursion and do as much practice as I can but I seem to be completely stumped on it when it comes to more difficult issues such as Recursive functions and using it in Linked Lists and Trees.
Here I am simply trying to reverse a linked list, using recursion at the leetcode question available here - https://leetcode.com/problems/merge-two-sorted-lists/. While there are solutions available, I'd like to know if possible as to why my code doesn't work as when I print out the values the correct ones seem to show up but I can't figure it out why it is not linking properly. Any help is appreciated.
Thank you
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution
{
static ListNode temp = new ListNode();
public ListNode mergeTwoLists(ListNode l1, ListNode l2)
{
//Base case, return temp listNode
if(l1 == null && l2 == null) return temp;
//If l1 has been used up and l2 not
if(l1 == null && l2 != null)
{
temp.next = l2;
l2 = l2.next;
}
//If l2 has been used up and l1 not
if(l2 == null && l1 != null)
{
temp.next = l1;
l1 = l1.next;
}
//If both nodes exist
if(l2 != null && l1 != null)
{
if(l2.val <= l1.val)
{
temp.next = l2;
l2 = l2.next;
}
else
{
temp.next = l1;
l1 = l1.next;
}
}
System.out.println(temp.val + " next " + temp.next.val);
temp = temp.next;
return mergeTwoLists(l1,l2);
}
}
badcome from?