HomeGorakh Raj Joshi

Merge Two Sorted Lists

Time Complexity O(m+n)/Space Complexity O(1)

  • #LeetCode

https://leetcode.com/problems/merge-two-sorted-lists/description

var mergeTwoLists = function (l1, l2) {
  let dummy = new ListNode();
  console.log(dummy);
  let current = dummy;

  while (l1 !== null && l2 !== null) {
    if (l1.val < l2.val) {
      current.next = l1;
      l1 = l1.next;
    } else {
      current.next = l2;
      l2 = l2.next;
    }
    current = current.next;
  }

  current.next = l1 !== null ? l1 : l2;

  return dummy.next;
};

Gorakh Raj Joshi

Senior Fullstack Engineer: Specializing in System Design and Architecture, Accessibility, and Frontend Interface Design

LinkedIn

GitHub

Email

All rights reserved © Gorakh Raj Joshi 2024