본문 바로가기
Programming/LeetCode

[LeetCode] Merge Two Sorted Lists

by 데이터현 2022. 3. 23.

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

정렬된 두 연결 리스트를 크기 순서대로 정렬하여 병합하는 문제

1. list1과 list2를 비교해 주면서 merge_list에 추가

2. 원소가 남은 친구들을 추가

# 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]:
        merge_list = ListNode()
        head = merge_list
        
        while list1 and list2:
            if list1.val <= list2.val:
                head.next = ListNode(val=list1.val)
                head = head.next
                list1 = list1.next
            else:
                head.next = ListNode(val=list2.val)
                head = head.next
                list2 = list2.next
        while list1:
            head.next = ListNode(val=list1.val)
            head = head.next
            list1 = list1.next
        while list2:
            head.next = ListNode(val=list2.val)
            head = head.next
            list2 = list2.next
        return merge_list.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

 

 

뭔가 풀면서 이렇게 풀수 있을 것 같았는데 신기하군.

코드 하나하나가 세심하게 잘 짜였다.

'Programming > LeetCode' 카테고리의 다른 글

[LeetCode] Reverse Linked List  (0) 2022.03.23
[LeetCode] Broken Calculator  (0) 2022.03.23
[LeetCode] Palindrome Linked List  (0) 2022.03.23
[LeetCode] Reverse String  (0) 2022.02.28
[LeetCode] Valid Palindrome  (0) 2022.02.25

댓글