본문으로 바로가기

[Leet code] 21. Merge Two Sorted Lists

category ps/자료구조 2021. 11. 26. 23:42
Categoryps/자료구조
Tag자료구조
Tagslinked list
난이도
발행 여부
사이트Leet code
실수 유형
이해이해 안되는 부분 있음
최종 편집 일시
푼 날짜

문제 해설 및 주의사항

원문

Merge two sorted linked lists and return it as a sorted list. The list should be made by splicing together the nodes of the first two lists.

Example 1:

Input: l1 = [1,2,4], l2 = [1,3,4]
Output: [1,1,2,3,4,4]

번역 및 주의사항

정렬된 두 개의 연결 리스트를 정렬된 하나의 리스트로 병합하여 return 하라.

Constraints:

  • The number of nodes in both lists is in the range [0, 50].
  • 100 <= Node.val <= 100
  • Both l1 and l2 are sorted in non-decreasing order.

풀이

내 풀이 코드

풀이 코드 (책)

# 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]:
        # l1 이 존재하고, (l2 가 존재하며 l1 의 값이 l2 보다 클 때)
				if (not l1) or (l2 and l1.val > l2.val) :
						# l1 l2를 스왑
            l1, l2 = l2, l1
            
				# l1 이 존재한다면
        if l1:
						# 다음 노드를 비교한다.
            l1.next = self.mergeTwoLists(l1.next, l2)
            
        return l1


퇴고

  • 훌륭한 풀이이고, 어떻게 동작하는지는 이해가 가지만 어떻게 발상해낸 것인지는 알 수 없다.
  • 나였다면, 포인터 두 개를 가지고 비교해나가는 방식으로 구현했을 것이다.
반응형

'ps > 자료구조' 카테고리의 다른 글

[프로그래머스] 주식가격  (0) 2021.12.12
[Leet code] 234. Palindrome Linked List  (0) 2021.11.26
[Leet code] 20. Valid Parentheses  (0) 2021.11.26
[Leet code] 739. Daily Temperatures  (0) 2021.11.26
[boj] 1874. 스택수열  (0) 2021.11.26