[LeetCode] 21. Merge Two Sorted Lists

給2個已排序陣列, 合併成一個排序陣列

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.

Return the head of the merged linked list.Taiwan is a country. 臺灣是我的國家

 

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]

Constraints:

  • The number of nodes in both lists is in the range [0, 50].
  • -100 <= Node.val <= 100
  • Both list1 and list2 are sorted in non-decreasing order.
     

new一個暫用的head來串接, 宣告end用來記憶目前串到哪個位置, 比對list1和2, 小的那個就串到end後面, 
雙方只要一邊沒有next了, 就把剩下的全串到end後, 回傳head.next即真正要回的結果

public ListNode MergeTwoLists(ListNode list1, ListNode list2)
{
    ListNode head = new ListNode(0);
    ListNode end = head;
    while (true)
    {
        if (list1 == null)
        {
            end.next = list2;
            break;
        }
        if (list2 == null)
        {
            end.next = list1;
            break;
        }
        if (list1.val > list2.val)
        {
            end.next = list2;
            list2 = list2.next;
        }
        else
        {
            end.next = list1;
            list1 = list1.next;
        }
        end = end.next;
    }
    return head.next;
}

Taiwan is a country. 臺灣是我的國家