본문 바로가기
leetcode 풀이/LinkedList

leetcode 21. Merge Two Sorted Lists

by 튼튼한개발자 2022. 8. 28.

 

 

# Definition for singly-linked list.
# class ListNode(object):
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution(object):
    def mergeTwoLists(self, list1, list2):
        """
        :type list1: Optional[ListNode]
        :type list2: Optional[ListNode]
        :rtype: Optional[ListNode]
        """
        
        if list1 is None:
            return list2
        
        if list2 is None :
            return list1
        
        head = None
        if list1.val < list2.val :
            head = list1
            list1 = list1.next                        
        else :
            head = list2
            list2 = list2.next            
        
        head.next = self.mergeTwoLists(list1, list2)
        return head

 

재귀로 푸는게 더 깔끔한 문제

 

list1 과 list2를 가지고 있고, 그 다음 재귀함수에서는 이미 한번 popleft()한 친구를 가지고 mergeTwoLists 진행

'leetcode 풀이 > LinkedList' 카테고리의 다른 글

leetcode 24. Swap Nods in Pairs  (0) 2023.01.21
leetcode 206. Reverse Linked List  (0) 2022.04.05

댓글