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.code
Solution 1:ip
class Solution { public ListNode mergeTwoLists(ListNode l1, ListNode l2) { if (l1==null && l2==null){ return null; } if( l1==null ){ return l2; } if(l2 == null){ return l1; } ListNode p1 = l1; ListNode p2 = l2; ListNode answer = null; if (p1.val<p2.val){ answer = p1; p1 = p1.next; }else{ answer = p2; p2 = p2.next; } ListNode p = answer; while(p1!=null & p2!=null){ if(p1.val < p2.val){ p.next = p1; p1 = p1.next; p = p.next; }else{ p.next = p2; p2 = p2.next; p = p.next; } } if (p1!=null){ p.next = p1; } if(p2!=null){ p.next = p2; } return answer; } }
Solution 2:ci
Using recursionleetcode
public ListNode mergeTwoLists(ListNode l1, ListNode l2){ if(l1==null) return l2; if(l2==null) return l1; if(l1.val < l2.val){ l1.next = mergeTwoLists(l1.next, l2); return l1; }else{ l2.next = mergeTwoLists(l1, l2.next); return l2; } }