[Leetcode/Python] Merge Two Sorted Lists

지구인 ㅣ 2022. 8. 21. 13:41

728x90
Top Interview Questions 의 Easy Collection에 있는 문제입니다.   
문제는 여기서 볼 수 있습니다.

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.

 

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.

 

 

Code:

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

# recursively
class Solution:
    def mergeTwoLists(self, list1: Optional[ListNode], list2: Optional[ListNode]) -> Optional[ListNode]:
        if not list1 or not list2:
            return list1 or list2
        if list1.val < list2.val:
            list1.next = self.mergeTwoLists(list1.next, list2)
            return list1
        else:
            list2.next = self.mergeTwoLists(list1, list2.next)
            return list2

첫 번째 if문

- 빈 Sequence(String / Tuple / List)는 False 값을 가진다.
- 비지 않은 리스트를 반환한다.
- 두 리스트 모두 비지 않았을 경우, 앞서 언급된 list1를 반환한다.
- 하지만 첫 if문은 두 리스트 중 최소 하나의 리스트가 비었다는 전제가 있으므로 하나의 리스트만 반환될 것이다.
- 만약 두 리스트 모두 비었다면 빈 리스트가 반환된다.

 

두 번째 if문

- list1의 첫 원소가 두 리스트 모두의 원소중 가장 작은 경우이다.

- 두 리스트를 합칠 때 제일 먼저 와야하는 원소가 list1의 첫 원소인 셈이다.

- 두 리스트의 탐색 원소를 순차적으로 보면서, 더 작은 원소의 다음 원소가 무엇이 될지 재귀적으로 탐색한다.

 

else문

- list2의 첫 원소가 두 리스트 모두의 원소중 가장 작은 경우이다.

- 두 리스트를 합칠 때 제일 먼저 와야하는 원소가 list2의 첫 원소인 셈이다.

- 두 리스트의 탐색 원소를 순차적으로 보면서, 더 작은 원소의 다음 원소가 무엇이 될지 재귀적으로 탐색한다.

 

728x90