1ms : Java Solution


  • 0
    S
    public class Solution {
        public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
    	      
    	      if(l1 == null) return l2;
    	      else if(l2 == null) return l1;
    	      
    	    
    	      ListNode newNode = new ListNode(0);
    	      ListNode rootNode = newNode;
    	      while(true){
    	          
    	          if(l1 != null && l2 != null){
    	        	  
    	               if(l1.val <= l2.val ){
    	                   newNode.next = new ListNode(l1.val);
    	                   l1 = l1.next;
    	               }else{
    	                   newNode.next = new ListNode(l2.val);
    	                   l2 = l2.next;
    	               }
    	               
    	               newNode = newNode.next;
    	          }else{
    	              if(l1 == null) {
    	                  l1 = l2;
    	              }	              
    	              //Copy all remaining elements
    	              newNode.next = l1;
    	              l2 = null;l1 = null;
    	          }
    	          
    	           if(l1 == null && l2 == null)  break;
    	          	          
    	      }
    	      
    	       return rootNode.next ;
        }
    }

Log in to reply
 

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