[Help] Getting run time error, although I handle null case?! works locally.


  • 0
    M
    public class Solution {
        public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
            
            if (l1 == null)
                return l2;
            
            if (l2 == null)
                return l1;
                
            ListNode l1p = l1;
            ListNode l2p = l2;
            ListNode head = null;
            
            if (l1p.val < l2p.val){
                head = l1p;
                l1p = l1p.next;
            }else{
                head = l2p;
                l2p = l2p.next;
            }
            
            ListNode merged = head;
    
            while (l1p != null && l2p != null){
                if (l1p.val < l2p.val){
                    merged.next = l1p;
                    merged = merged.next;
                    l1p = l1p.next;
                }else{
                    merged.next = l2p;
                    merged = merged.next;
                    l2p = l2p.next;
                }
            }
            
            if (l1p == null){
                while (l2p != null){
                    merged.next = l2p;
                    merged = merged.next;
                    l2p = l2p.next;
                }
            }
            
            if (l2p == null){
                while (l1p != null){
                    merged.next = l1p;
                    merged = merged.next;
                    l1p = l1p.next;
                }
            }
            
            return head;
        }

  • 0
    O

    Give us OJ message.


Log in to reply
 

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