## DEV Community ๐ฉโ๐ป๐จโ๐ป is a community of 963,864 amazing developers

We're a place where coders share, stay up-to-date and grow their careers.

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]
``````

### Explanation

็ตฆๅฎๅฉๅๅทฒๆๅบ็ Linked List๏ผๅๅฅ็บ `l1` ๅ `l2` ๏ผๅฐๅฉๅ Linked List ๅไฝตๆไธๅ Linked List๏ผไธฆไธ่ฉฒ้็ตไธฒๅๅฟ้ ้้ๅฉๅ้็ตไธฒๅ็็ฏ้ปๆผๆนๅจไธ่ตท๏ผ่ฟๅไธๅๅๆจฃๆๅบ็้็ตไธฒๅ๏ผ่ฟๅ็้็ตไธฒๅๅฟ้ ๆฏ็ฌฌไธๅ็ฏ้ป

### Solution

ไธ้ๅงๅๅคๆทๅฉๅ้็ตไธฒๅๆฏๅฆ็บ null๏ผๅฆๆๆไธๅๆฏ null๏ผๅ็ดๆฅ่ฟๅๅฆไธๅ้็ตไธฒๅ

้็ตไธฒๅๆฏ่ผ้ฃ่งฃ้๏ผ้ฆๅ่ฆๅ็ฅ้้็ตไธฒๅ็็นๆง๏ผๅฎๆฏๅฑฌๆผๅๆ่จๆถ้ซ้็ฝฎ๏ผ็บไบ่ฟๅๆๆจๅจ็ฌฌไธๅ็ฏ้ป็้็ตไธฒๅ๏ผๆๅปบ็ซๅฉๅ้็ตไธฒๅๅๅฅ็บ `res` ๅ `cur` ๏ผ`res` ๆฏๆ็ต่ฆ่ฟๅ็ๅผ๏ผ่ `cur` ๆฏ็จไพๅไฝตๆไฝฟ็จ็๏ผไธฆไธ่ฎ `cur = res` ๏ผ็ถ `cur` ่ขซ่ฎๆดๆ๏ผ`res` ไนๆๆ็ธๅ็่ฎๅ๏ผๅ ็บๆๆจๆฌๆฏๆๅๅไธๅก่จๆถ้ซไฝ็ฝฎ

ไฝฟ็จ `while` ๅท่กๅฉๅ้็ตไธฒๅ็ถๅๅผ็ๆฏ่ผ๏ผๅผๆฏ่ผๅฐ็ๅฐฑๅฐ็ถไธ็็ฏ้ปๆ็ตฆ `cur.next` ๏ผไธฆๅฐๅถ็งปๅๅฐไธไธๅๆๆจ่จ้็่จๆถ้ซไฝ็ฝฎ๏ผๆๅพๅฐ `cur` ็งปๅๅฐไธไธๅๆๆจ่จ้็่จๆถ้ซไฝ็ฝฎ๏ผไปฅ็นผ็บ้ฃ็ตๆฅไธไพ็ๆฏ่ผ็ตๆ็ฏ้ป๏ผ็ดๅฐไปปไธ้็ตไธฒๅ็บ null ๆๅฐฑ็ตๆ่ฟดๅไฝๆฅญ๏ผๆๅพๅฐๅฉ้คๆช้ฒ่กๆฏ่ผ็็ฏ้ป้ฃ็ตๅฐ `cur` ็ไธไธๅๆๆจๆฌ๏ผ็ถๅพๅไฝต็ตๆ `res.next`

``````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