Can anyone tell me why the second version is wrong?


  • 1
    M

    This is my first version that can pass the OJ:

    public class Solution {
        public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
            if(l1 == null) return l2;
            if(l2 == null) return l1;
            ListNode curr = new ListNode((l1.val < l2.val ? l1.val : l2.val));
            ListNode head = curr;
            ListNode index1 = l1.val < l2.val ? l1.next : l1;
            ListNode index2 = l1.val < l2.val ? l2: l2.next;
            while(index1 != null && index2 != null) {
                if(index1.val < index2.val) {
                    ListNode temp = new ListNode(index1.val);
                    curr.next = temp;
                    curr = temp;
                    index1 = index1.next;
                } else {
                    ListNode temp = new ListNode(index2.val);
                    curr.next = temp;
                    curr = temp;
                    index2 = index2.next;
                }
            }
            if(index1 != null) curr.next = index1;
            if(index2 != null) curr.next = index2;
            return head;
        }
    }
    

    Then I tried to refine the code by putting the similar blocks into a function. However, it did not work and I got "Time Limit Exceeded". The updated code is:

    public class Solution {
        public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
            if(l1 == null) return l2;
            if(l2 == null) return l1;
            ListNode curr = new ListNode((l1.val < l2.val ? l1.val : l2.val));
            ListNode head = curr;
            ListNode index1 = l1.val < l2.val ? l1.next : l1;
            ListNode index2 = l1.val < l2.val ? l2: l2.next;
            while(index1 != null && index2 != null) {
                if(index1.val < index2.val) {
                    addNode(index1, curr);
                } else {
                    addNode(index2, curr);
                }
            }
            if(index1 != null) curr.next = index1;
            if(index2 != null) curr.next = index2;
            return head;
        }
        
        public void addNode(ListNode nodeToBeAdded, ListNode curr) {
            ListNode temp = new ListNode(nodeToBeAdded.val);
            curr.next = temp;
            curr = temp;
            nodeToBeAdded = nodeToBeAdded.next;
        }
    }
    

    Can anyone tell what is the error in the second version?


  • 0
    F

    First of all, you don't need to create a new node!

    Here is why your second version did not workl. Java is passing the reference val. You "index1" and "curr" never changed when you pass them to addNode.


Log in to reply
 

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