Search code examples
javascriptlinked-list

How to run leetcode linked list problems in local machine?


How can I run the linked list programs in the local machine? When I run this code in their input box it running but I can't seem to run this program in the local machine.

  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 (l1, l2) {
  var mergedHead = { val: -1, next: null },
    crt = mergedHead;
  while (l1 && l2) {
    if (l1.val > l2.val) {
      crt.next = l2;
      l2 = l2.next;
    } else {
      crt.next = l1;
      l1 = l1.next;
    }
    crt = crt.next;
  }
  crt.next = l1 || l2;
  return mergedHead.next;
};

mergeTwoLists([1, 2, 4], [1, 3, 4]);

Solution

  • You could use these two helper functions to convert an array to linked list and vice versa, which is essentially what the LeetCode framework does for you behind the scenes.

    const listFromArray = a => a.length ? new ListNode(a[0], listFromArray(a.slice(1)))  
                                        : null;
    const arrayFromList = head => head ? [head.val].concat(arrayFromList(head.next)) 
                                       : [];
    

    In your case you can use them like this:

    const result = arrayFromList(
        mergeTwoLists(listFromArray([1, 2, 4]), listFromArray([1, 3, 4]))
    );