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.
Subscribe to see which companies asked this question
1 /** 2 * Definition for singly-linked list. 3 * public class ListNode { 4 * int val; 5 * ListNode next; 6 * ListNode(int x) { val = x; } 7 * } 8 */ 9 public class Solution { 10 public ListNode mergeTwoLists(ListNode l1, ListNode l2) { 11 if(l1 == null) return l2; 12 if(l2 == null) return l1; 13 ListNode res = new ListNode(-1); 14 ListNode pre = new ListNode(-1); 15 res.next = pre; 16 while(l1!= null && l2 != null){ 17 if(l1.val <= l2.val){ 18 pre.next = l1; 19 l1 = l1.next; 20 }else{ 21 pre.next = l2; 22 l2 = l2.next; 23 } 24 pre = pre.next; 25 } 26 if(l1 != null) pre.next = l1; 27 if(l2 != null) pre.next = l2; 28 return res.next.next; 29 } 30 }