Merge two sorted linked lists and return it as a new list. The new list should be made by splicing together the nodes of the first two lists.
Analysis
The key to solve the problem is defining a fake head. Then compare the first elements from each list. Add the smaller one to the merged list. Finally, when one of them is empty, simply append it to the merged list, since it is already sorted.
C++ Solution
<span style="font-size:14px;">ListNode mergeTwoLists(ListNode L1, ListNode L2){
ListNode p1 = L1;
ListNode P2 = L2;
ListNode fakeHead = new ListNode(0);
ListNode p = fakeHead;
while(p1 != null && p2 != null){
if(p1.val <= P2.val){
p.next = p1;
p1 = p1.next;
}else{
p.next = p2;
p2 = p2.next;
}
p = p.next;
}
if(p1 != null)
p.next = p1;
if(p2 != null)
p.next = p2;
return fakeHead.next;
}</span>
ListNode mergeTwoLists(ListNode L1, ListNode L2){
if(L1 == NULL)
return L2;
if(L2= NULL)
return L1;
ListNode p1 = L1;
ListNode p2 = L2;
ListNode fakeHead = new ListNode(0);
ListNode p = fakeHead;
if(p1.val < = p2.val){
p.next = mergeTwoLists(p1.next, p2);
}else{
p.next = mergeTwoLists(p1, p2.next);
}
p = p.next;
if(p1 != null)
p.next = p1;
if(p2 != null)
p.next = p2;
return fakeHead.next;
}