Here is the link to the question : https://leetcode.com/problems/merge-in-between-linked-lists/
Here is my solution:
class Solution {
public ListNode mergeInBetween(ListNode list1, int a, int b, ListNode list2) {
ListNode end2 = null;
ListNode start2 = list2;
while(start2.next!=null)
{
start2 = start2.next;
}
end2 = start2;
ListNode fakeNode = new ListNode(-1);
fakeNode.next = list1;
ListNode prev = fakeNode;
ListNode actual = list1;
while(actual!=null)
{
if(actual.val == a)
{
prev.next = list2;
break;
}
actual = actual.next;
prev = prev.next;
}
while(actual.next!=null)
{
if(actual.val == b)
{
end2.next = actual.next;
end2 = end2.next;
break;
}
actual = actual.next;
}
// end2.next = null;
return fakeNode.next;
}
}Leetcode ans and my ans differs on TC:
[0,3,2,1,4,5]
3
4
[1000000,1000001,1000002]
My Output:[0,1000000,1000001,1000002,5]
LeetCode Output : [0,3,2,1000000,1000001,1000002,5]
According to question and my understanding we have to remove all elements between 3 and 4 (inclusive) and add the second list at that place . So ans should be 0 (remove)[,3,2,1,4 ] (add)[1000000,1000001,1000002] (remaining) [5] so final ans should be [0 1000000,1000001,1000002 5] . Kindly correct me if I am wrong.
Thanks.