자료구조와 알고리즘/🥑알고리즘

[알고리즘][연결 리스트] - 2. 두 정렬 리스트의 병합

얄루몬 2022. 2. 24. 23:02

 

📖이 포스팅은 '파이썬 알고리즘 인터뷰 - 박상길님'을 보고 작성되었습니다.


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

정렬되어 있는 두 연결 리스트를 합쳐라


[재귀 구조로 연결]

# 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]:
        if (not list1) or (list2 and list1.val > list2.val):
            list1, list2 = list2, list1
        if list1:
            list1.next = self.mergeTwoLists(list1.next, list2)
        return list1