You’re given the pointer to the head nodes of two sorted linked lists. The data in both lists will be sorted in ascending order. Change the next
pointers to obtain a single, merged linked list which also has data in ascending order. Either head pointer given may be null meaning that the corresponding list is empty.
Input Format
You have to complete the SinglyLinkedListNode MergeLists(SinglyLinkedListNode headA, SinglyLinkedListNode headB)
method which takes two arguments – the heads of the two sorted linked lists to merge. You should NOT read any input from stdin/console.
The input is handled by the code in the editor and the format is as follows:
The first line contains an integer t, denoting the number of test cases.
The format for each test case is as follows:
The first line contains an integer n, denoting the length of the first linked list.
The next n lines contain an integer each, denoting the elements of the linked list.
The next line contains an integer m, denoting the length of the second linked list.
The next m lines contain an integer each, denoting the elements of the second linked list.
Constraints
- 1 <= t <= 10
- 1 <= n <= 1000
- 1 <= list’i <= 1000, where list’i is the i’th element of the list.
Output Format
Change the next
pointer of individual nodes so that nodes from both lists are merged into a single list. Then return
the head of this merged list. Do NOT print anything to stdout/console.
The output is handled by the editor and the format is as follows:
For each test case, print in a new line, the linked list after merging them separated by spaces.
Sample Input
1
3
1
2
3
2
3
4
Sample Output
1 2 3 3 4
Explanation
The first linked list is: 1 -> 2 -> 3 -> NULL
The second linked list is: 3 -> 4 -> NULL
Hence, the merged linked list is: 1 -> 2 -> 3 -> 3 -> 4 -> NULL
Code:
static SinglyLinkedListNode mergeLists(SinglyLinkedListNode head1, SinglyLinkedListNode head2) {
if(head1 == null) {
return head2;
}
if(head2 == null) {
return head1;
}
if(head1.data < head2.data) {
head1.next = mergeLists(head1.next, head2);
return head1;
} else {
head2.next = mergeLists(head1, head2.next);
return head2;
}
}
Hope you guys understand the simple solution of inserting a node at tail in linked list in java.
For practicing the question link is given https://www.hackerrank.com/challenges/merge-two-sorted-linked-lists/problem
In next blog we will see other operations on linked list till then Bye Bye..!
Thanks for reading…!
Happy Coding..!
Thank You…!
Hello.
I have used your code in HackerRank but it failed to satisfy two test cases.
I think you have to modify your code.
please let me know if I am wrong
LikeLike