Reputation: 63
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);
}
}
Upvotes: 0
Views: 73
Reputation: 11
Your base case is to return temp, which you have at the beginning of the method.
And for every iteration you are overwriting the value of temp, at the end of the method.
So you end up having just the latest value in temp, losing all the previous values.
You should focus on resolving this problem without using variables which are external to the mergeTwoLists method.
Upvotes: 1
Reputation: 1
Have you tried using temp.setNext()
to set your next node?
I suggest you take a look at this it might help you with ListNodes
https://www2.cs.duke.edu/csed/ap/subset/doc/ap/ListNode.html
Upvotes: 0