Java solution without the use of prev / beats 86%


  • 0
    D
    public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
            ListNode head1=null;
            ListNode head2=null;
            if(l1==null && l2!=null)
                return l2;
            else if(l1!=null && l2==null)
                return l1;
            else if(l1==null && l2==null)
                return l1;
                
            if(l1.val<l2.val){
            	 head1= l1;
            	 head2=l2;
        	}else{
            	 head2=l1;
            	 head1=l2;
        	}
        
            ListNode root = head1;
        
            while(head2!=null){
        	    while((head1!=null && head1.val < head2.val) && 
                         (head1.next!=null && head1.next.val<head2.val)){
        		    head1=head1.next;
        	    }
        
        	    ListNode p2 = head2.next;
        
        	    head2.next=head1.next;
        	    head1.next=head2;
        	    head1=head1.next;
        	    head2=p2;
        
            }
        
            return root;
        }
    

Log in to reply
 

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