Java solution xxxxxxxx


  • 0
    V

    public class Solution {

    public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
    
      if(l1 == null && l2 == null){
          return null;
      }  
      if(l1 == null && l2 != null){
          return l2;
      }
      if(l1 != null && l2 == null){
          return l1;
      }
     
     ListNode node = new ListNode(0);
     ListNode head = node;
     
     while(l1 != null && l2 != null){
         if(l1.val > l2.val){
             node.next = l2;
             l2 = l2.next;
         }else{
             node.next = l1;
             l1 = l1.next;
         }
         node = node.next;
     }
     
     if(l1 == null){
         node.next = l2;
     }else{
         node.next = l1;
     }
     head = head.next; 
     return head;  
    }
    

    }


  • 0
    F

    public static ListNode mergeTwoLists(ListNode l1, ListNode l2) {
    ListNode l3;

    	if (l1 == null || l2 == null) {
    		l3 = l1 == null ? l2 : l1;
    		return l3;
    	}
    
    	if (l1.val < l2.val) {
    		l3 = l1;
    		l1 = l1.next;
    	} else {
    		l3 = l2;
    		l2 = l2.next;
    	}
    	ListNode pre = l3;
    	while (l1 != null || l2 != null) {
    		if (l1 == null || l2 == null) {
    			pre.next = l1 == null ? l2 : l1;
    			break;
    		} else {
    			if (l1.val < l2.val) {
    				pre.next = l1;
    				l1 = l1.next;
    			} else {
    				pre.next = l2;
    				l2 = l2.next;
    			}
    
    			pre = pre.next;
    		}
    	}
    
    	return l3;
    }

Log in to reply
 

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