Merge sorted linked list

Please tell what is the error.
link :

question :
MERGE SORTED LINKED LISTS
Given 2 sorted linked lists , Merge the two given sorted linked list and print the final LinkedList.

Input Format:
First Line contains T the number of test cases. For each test case : Line 1 : N1 the size of list 1 Line 2 : N1 elements for list 1 Line 3 : N2 the size of list 2 Line 4 : N1 elements for list 2

Constraints:
1 <= T <= 1000 0<= N1, N2 <= 10^6 -10^7 <= Ai <= 10^7

Output Format
T lines of merged output

Sample Input
1
4
1 3 5 7
3
2 4 6
Sample Output
1 2 3 4 5 6 7

Hello @poorva2145,

Your code will fail for the case when either of the two linked list is empty i.e. there are 0 elements in that linked list.
Example:
1
0
4
1 3 5 7
Your Output:
3 4
Expected Output:
1 3 5 7
Reason:
Your are reading atleast 1 element for both linked list irrespective of the value of n (i.e. their length)
Thus, after reading 0 as n. It will read 4 as key and insert at head of list 1.
Then reading 1 as n. It will read 3 as key and insert it at head of list 2.

Modified Code:

Hope, this would help.
Give a like if you are satisfied.

1 Like