Java beats 85% solutions


  • 0
    S
    /**
     * Definition for singly-linked list.
     * public class ListNode {
     *     int val;
     *     ListNode next;
     *     ListNode(int x) { val = x; }
     * }
     */
    public class Solution {
        public ListNode mergeTwoLists(ListNode l1, ListNode l2)
    {
        if (l1 == null)
            return l2;
        if (l2 == null)
            return l1;
        
        ListNode head = null;
        if (l1.val < l2.val)
        {
            head = new ListNode(l1.val);
            //head.next = new ListNode(l2.val);
            l1=l1.next;
            //l2 = l2.next;
        }
        else 
        {
            head = new ListNode(l2.val);
            //head.next = new ListNode(l1.val);
            //l1 = l1.next;
            l2=l2.next;
        }
        
        ListNode main_node= head;
            //head=head.next;
        while (l1 != null || l2 != null)
        {
            //System.out.println("l1 : " + l1.val);
            //System.out.println("l2 : " + l2.val);
            
            if(l1!=null && l2!=null){
            if (l1.val < l2.val)
            {
                head.next = new ListNode(l1.val);
                head=head.next;
                //head.next = new ListNode(l2.val);
                //head=head.next;
                l1=l1.next;
                //l2 = l2.next;
            }
            else // l1.val < l2.val
            {
                head.next = new ListNode(l2.val);
                head=head.next;
                //head.next = new ListNode(l1.val);
                //head=head.next;
                //l1=l1.next;
                l2 = l2.next;
            }
            }
            //curNode = curNode.next;
             else if (l1 != null){
                head.next = new ListNode(l1.val);
                 l1=l1.next;
                head=head.next;
             }
            else if (l2 != null){
                head.next = new ListNode(l2.val);
                l2=l2.next;
                head=head.next;
            }
        }
       
            
        return main_node;
    }
    }
    
    

Log in to reply
 

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