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

method which takes two arguments – the heads of the two sorted linked lists to merge. You should NOT read any input from stdin/console.**SinglyLinkedListNode****MergeLists(SinglyLinkedListNode headA, SinglyLinkedListNode headB)**

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

*lines contain an integer each, denoting the elements of the linked list.*

**n**The next line contains an integer

*, denoting the length of the second linked list.*

**m**The next

*lines contain an integer each, denoting the elements of the second linked list.*

**m****Constraints**

**1 <= t <= 10****1 <= n <= 1000**, where list’i is the**1 <= list’i <= 1000**element of the list.**i’th**

**Output Format**

Change the `next`

pointer of individual nodes so that nodes from both lists are merged into a single list. Then

the head of this merged list. Do NOT print anything to stdout/console.**return**

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…!**

Categories: HackerRank Questions, Interview, JAVA

## Leave a Reply