My JAVA solution, share is the keyword


  • 0
    R
    public class Solution {
        public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
            if (l1==null) return l2;
            else if(l2==null) return l1;
            
            ListNode dummy = new ListNode(0);
            ListNode head=dummy;
            while(l1!=null||l2!=null){
                if((l1==null?Integer.MAX_VALUE:l1.val)<=(l2==null?Integer.MAX_VALUE:l2.val)){
                    dummy.next=l1;
                    l1 = l1==null? l1:l1.next;
                }else{
                    dummy.next=l2;
                    l2 = l2==null? l2:l2.next;
                }
                dummy=dummy.next;
    
            }
            return head.next;
        }
    }

  • 1
    H
     //Easy read logic
    public class Solution {
        public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
            if (l1==null) return l2;
            if (l2==null) return l1;
            
            ListNode dummy = new ListNode(0);
            ListNode head = dummy;
            while (l1!= null && l2 != null) {
                if(l1.val > l2.val){
                    dummy.next = l2;
                    l2 = l2.next;
                    
                } else {
                    dummy.next = l1;
                    l1 = l1.next;
                }
                dummy = dummy.next;
            }
            
            if (l1 == null) {
                dummy.next = l2;
            } else {
                dummy.next = l1;
            }
            
            return head.next;
            
            
            
        }

  • 0
    R

    nice! yours is better than my solution. I was thinking straightforward while coding, like bad habits. :C


  • 0
    V

    Why we can't just set "dummy = l2" instead of " dummy.next = l2" if l1.val > l2.val and "dummy = l1" if l1.val < l2.val, then just return head?


  • 0
    H

    ListNode dummy = new ListNode(0); this is a dummy node is not part of list. Kind of helper field in LinkList related programming practice.


Log in to reply
 

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