PROBLEM DESCRIPTION
Given two sorted linked lists consisting of nodes respectively. The task is to merge both lists and return the head of the merged list.
SOLUTION
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
class Solution {
Node sortedMerge(Node head1, Node head2) {
Node h1 = head1;
Node h2 = head2;
Node dummyHead = new Node(0);
Node tail = dummyHead;
while (h1 != null && h2 != null) {
Node temp = null;
if (h1.data < h2.data) {
temp = h1;
h1 = h1.next;
} else {
temp = h2;
h2 = h2.next;
}
temp.next = null;
tail.next = temp;
tail = tail.next;
}
if (h1 != null)
tail.next = h1;
else
tail.next = h2;
return dummyHead.next;
}
}