본문 바로가기

Algorithm/파이썬 알고리즘 인터뷰 스터디

[연결리스트] 14 두 정렬 리스트의 병합(Merge Two Sorted Lists)

<LeetCode 문제>

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

 

Merge Two Sorted Lists - LeetCode

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com

정렬되어 있는 두 연결 리스트를 합치는 문제입니다. 이때, 각 리스트가 정렬된 상태라는 점이 중요합니다.

<풀이>

병합 정렬의 마지막 조합과 동일한 방식으로 재귀를 통해 코드를 작성하면 다음과 같습니다.

# 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, l1: Optional[ListNode], l2: Optional[ListNode]) -> Optional[ListNode]:
        if (not l1) or (l2 and l1.val > l2.val):
            l1,l2=l2,l1
        if l1:
            l1.next = self.mergeTwoLists(l1.next,l2)
        return l1

 

<학습내용>

1.

<학습이 필요한 내용>

1. 병합 정렬 내용 학습

 

https://github.com/HoYoungChun/Algorithm_PS/blob/master/Python_Study/08_linked_list/LC_21.py

 

GitHub - HoYoungChun/Algorithm_PS: Baekjoon Online Judge, Programmers, LeetCode problem solving by Python, C++

Baekjoon Online Judge, Programmers, LeetCode problem solving by Python, C++ - GitHub - HoYoungChun/Algorithm_PS: Baekjoon Online Judge, Programmers, LeetCode problem solving by Python, C++

github.com