Pages

Thursday, September 18, 2025

Leetcode 21. Merge two lists using Linked list in Java (with mistakes noted)

MY MISTAKE:
 if(list1 == null) {

    return list1;   // ❌ This should return list2, not list1

}


if(list2 == null) {

    return list2;   // ❌ This should return list1, not list2

}


👉 Reason:

  • If list1 is null, that means no nodes are left in list1, so you should just return the other list (list2).

  • Similarly, if list2 is null, you should return list1.


CODE:

class Solution {
    public ListNode mergeTwoLists(ListNode list1, ListNode list2) {
        if(list1 == null) {
            return list2;
        }

        if(list2 == null) {
            return list1;
        }

        if(list1.val < list2.val) {
            list1.next = mergeTwoLists(list1.next, list2);
            return list1;
        } else {
            list2.next = mergeTwoLists(list1, list2.next);
            return list2;
        }
    }
}

No comments:

Post a Comment

remove duplicates from sorted array - two pointer approach (leetcode)

  class Solution {     public int removeDuplicates ( int [] nums ) {         // base case: return if array have no el.         if ( nums...