Skip to content

Latest commit

 

History

History
56 lines (39 loc) · 1.61 KB

File metadata and controls

56 lines (39 loc) · 1.61 KB

👨🏻‍✈️ LeetCode 21. Merge Two Sorted Lists

  • Date : 2021.07.25(일)
  • Time : 20분

Problem

  • 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.

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.

Example

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



풀이

    def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode:
        
        if not l1 : return l2
        if not l2 : return l1

        pool = []

        if l1:
            while l1.next:
                pool.append(l1.val)
                l1 = l1.next
            pool.append(l1.val)

        if l2:
            while l2.next:
                pool.append(l2.val)
                l2 = l2.next
            pool.append(l2.val)

        pool.sort()

        head = ListNode(pool.pop(0))
        curr = head

        while pool:
            curr.next = ListNode(pool.pop(0))
            curr = curr.next

        return head

: 그냥 배열이 아니라 리트코드에서 만들어 둔 ListNode Class 를 활용해야했다. 먼저 두 배열을 보고 한 쪽이라도 배열이 빈 상태라면 다른 배열을 출력하였다. 만약 두 배열에 모두 값이 있을 때 진행하였다. 먼저 l1배열부터 l2까지 ListNode를 이용하여 배열에 추가해주었다. 그리고 내가 만든 배열도 ListNode 배열로 다시 수정해주었다. ListNode에 대한 이해가 필요한 문제였다.