Java Iteration Solution without stack overflowing problem


  • 0
    Y

    class Solution {
    public ListNode mergeTwoLists(ListNode l1, ListNode l2) {

        ListNode result = new ListNode(-9999);
        ListNode temp = result;
        ListNode a=l1;
        ListNode b=l2;
    
        
        while(a!=null&&b!=null){
            
            if(a.val<b.val){
                temp.val =a.val;
                a = a.next;
            }
            else{
                temp.val =b.val;
                b =b.next;
            }
            temp.next = new ListNode(-9999);
            temp = temp.next;
    
        }
        if(a!=null){
            temp.val = a.val;
            temp.next = a.next;
        }
        else if(b!=null){
            temp.val = b.val;
            temp.next = b.next;
        }
        else{
            return a;
        }
        return result;
        
    }
    

    }


Log in to reply
 

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