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.
1 /** 2 * Definition for singly-linked list. 3 * public class ListNode { 4 * int val; 5 * ListNode next; 6 * ListNode(int x) { 7 * val = x; 8 * next = null; 9 * } 10 * } 11 */ 12 public class Solution { 13 public ListNode mergeTwoLists(ListNode l1, ListNode l2) { 14 // Start typing your Java solution below 15 // DO NOT write main() function 16 if(l1 == null){ 17 return l2; 18 } 19 if(l2 == null){ 20 return l1; 21 } 22 ListNode head = new ListNode(-1); 23 ListNode tmp = head; 24 while(l1 != null && l2 != null){ 25 if(l1.val < l2.val){ 26 tmp.next = l1; 27 l1 = l1.next; 28 } else { 29 tmp.next = l2; 30 l2 = l2.next; 31 } 32 tmp = tmp.next; 33 } 34 35 if(l1 != null){ 36 tmp.next = l1; 37 } 38 if(l2 != null){ 39 tmp.next = l2; 40 } 41 return head.next; 42 } 43 }