FakeStandard

Posted on

Merge Two Sorted Lists

#21.Merge Two Sorted Lists

Problem statement

You are given the heads of two sorted linked lists `list1` and `list2`.

Merge the two lists in a one sorted list. The list should be made by splicing together the nodes of the first two lists.

Example 1

``````Input: list1 = [1,2,4], list2 = [1,3,4]
Output: [1,1,2,3,4,4]
``````

Example 2

``````Input: list1 = [], list2 = []
Output: []
``````

Example 3

``````Input: list1 = [], list2 = [0]
Output: [0]
``````

Solution

``````public ListNode MergeTwoLists(ListNode l1, ListNode l2)
{
if (l1 == null || l2 == null) return l1 ?? l2;

ListNode res = new ListNode(), cur = res;

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

cur = cur.next;
}

cur.next = l1 ?? l2;

return res.next;
}
``````

Reference

LeetCode Solution

GitHub Repository

Thanks for reading the article 🌷 🌻 🌼

If you like it, please don't hesitate to click heart button ❤️
or click like on my Leetcode solution