Java Solution


  • 0
    R
    /**
     * Definition for singly-linked list.
     * public class ListNode {
     *     int val;
     *     ListNode next;
     *     ListNode(int x) { val = x; }
     * }
     */
    class Solution {
        public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
            if(l2 == null) return l1;       
            if(l1 == null) return l2;
            
            ListNode sp = findNode(null, l1, l2.val);
            if(sp == null) {
                ListNode ep = findNode(null, l2, l1.val);
                if(ep.next == null) {
                    ep.next = l1;
                    return l2;
                }
                ListNode nP = ep.next;
                ep.next = l1;
                return mergeTwoLists(l2, nP);
            }else {
                if(sp.next == null) {
                    sp.next = l2;
                    return l1;
                }
                ListNode ep = findNode(l2, l2.next, sp.next.val);
                ListNode nL2 = ep.next;
                ep.next = sp.next;
                sp.next = l2;
                return mergeTwoLists(l1, nL2);
            }
            
        }
        
        ListNode findNode(ListNode ln, ListNode next, int val) {
            if(next == null || next.val > val) return ln;
            return findNode(next, next.next, val);
        }
        
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.