shaneB
shaneB

Reputation: 49

Leetcode 21 Question: Merge Two Sorted Lists, wants me to return empty list?

I am working on this question on leetcode, https://leetcode.com/problems/merge-two-sorted-lists/

I have written a (inefficient) solution:

/**
 * Definition for singly-linked list.
 * function ListNode(val, next) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.next = (next===undefined ? null : next)
 * }
 */
/**
 * @param {ListNode} list1
 * @param {ListNode} list2
 * @return {ListNode}
 */
var mergeTwoLists = function (list1, list2) {
  const arr = [];

  while (list1 || list2) {
    if (list1.val !== null) {
      arr.push(list1.val);
    }
    if (list2.val !== null) {
      arr.push(list2.val);
    }
    list1 = list1.next;
    list2 = list2.next;
  }

  arr.sort((a, b) => a - b);

  arr.forEach((el, index) => {
    arr[index] = new ListNode(el);
    if (index > 0) {
      arr[index - 1].next = arr[index];
    }
  });

  if (arr[0]) {
    return arr[0];
  }
  return new ListNode(null);
};

When I try to submit the code, I get the following error:

Input:
[]
[]
Output:
[0]
Expected:
[]

I don't understand how I am supposed to be returning an empty list like it is asking. If you look at the ListNode implementation they provide, it always defaults to instantiating a ListNode with a value of 0 if it is undefined.

As you can see at the bottom of my answer, I return new ListNode(null) if I am provided 2 empty lists, and this still results in the value being 0. Can someone please explain what I need to do to make this solution pass?

Thank you for you help.

Upvotes: 0

Views: 1050

Answers (1)

shaneB
shaneB

Reputation: 49

I found the solution. I was trying to return a list node, when I was supposed to return the head. instead of returning new ListNode(null), i simply needed to return null. Here is the solution:

/**
 * Definition for singly-linked list.
 * function ListNode(val, next) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.next = (next===undefined ? null : next)
 * }
 */
/**
 * @param {ListNode} list1
 * @param {ListNode} list2
 * @return {ListNode}
 */
var mergeTwoLists = function (list1, list2) {
  const arr = [];

  while (list1 !== null || list2 !== null) {
    if (list1) {
      arr.push(list1.val);
      list1 = list1.next;
    }
    if (list2) {
      arr.push(list2.val);
      list2 = list2.next;
    } 
  }

  arr.sort((a, b) => a - b);

  arr.forEach((el, index) => {
    arr[index] = new ListNode(el);
    if (index > 0) {
      arr[index - 1].next = arr[index];
    }
  });

  if (arr[0]) {
    return arr[0];
  }
  return null
};

Upvotes: 1

Related Questions