작심삼일

[LeetCode] 21 | Merge Two Sorted Lists | Python 본문

스터디/코테

[LeetCode] 21 | Merge Two Sorted Lists | Python

yun_s 2022. 3. 7. 10:22
728x90
반응형

문제 링크: https://leetcode.com/problems/merge-two-sorted-lists/


문제

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.


조건

  • 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.

내 풀이

list1과 list2의 현재 val을 비교하며 더 작은 것을 head에 추가한다.


코드

# 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()
        head = ans
        
        while list1 or list2:
            if list1 and list2:
                if list1.val < list2.val:
                    head.next = ListNode(list1.val)
                    list1 = list1.next if list1.next else None
                else:
                    head.next = ListNode(list2.val)
                    list2 = list2.next if list2.next else None
            elif list1:
                head.next = ListNode(list1.val)
                list1 = list1.next if list1.next else None
            elif list2:
                head.next = ListNode(list2.val)
                list2 = list2.next if list2.next else None
            
            head = head.next
            
        return ans.next
728x90
반응형
Comments