[leetcode] 21. Merge Two Sorted Lists _ Algorithm Problem Solve for python



1. Problem

21. Merge Two Sorted Lists

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

Merge the two lists into 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.

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:

  • 1 <= nums.length <= 5 * 10^5
  • -2^31 <= nums[i] <= 2^31 - 1

2. Solution

I solved this problem like this.

It is easy to solve. We just compare list value and push next.

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next

class Solution:
    def mergeTwoLists(self, list1: Optional[ListNode], list2: Optional[ListNode]) -> Optional[ListNode]:
        ans = ListNode()
        ans_end = ans
        l1, l2 = list1, list2
        while l1 and l2:
            if l1.val < l2.val:
                ans_end.next = l1
                ans_end = l1
                l1 = l1.next
            else:
                ans_end.next = l2
                ans_end = l2
                l2 = l2.next

        while l1:
            ans_end.next = l1
            ans_end = l1
            l1 = l1.next

        while l2:
            ans_end.next = l2
            ans_end = l2
            l2 = l2.next

        return ans.next