본문 바로가기
Python/PS in Python

LeetCode 21. Merge Two Sorted Lists - Python

by Air’s Big Data 2020. 8. 21.

LeetCode 21. Merge Two Sorted Lists - Python

 

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

 

Example:

Input: 1->2->4, 1->3->4
Output: 1->1->2->3->4->4

 

Solution :

class Solution:
    def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode:
        if l1 is None :
            return l2

        if l2 is None :
            return l1

        if (l1.val > l2.val) :
            head = ListNode(l2.val)
            head.next = self.mergeTwoLists(l1, l2.next)
        else :
            head = ListNode(l1.val)
            head.next = self.mergeTwoLists(l1.next, l2)

        return head

(References)

솔루션 출처 : https://rottk.tistory.com/entry/21-Merge-Two-Sorted-Lists

알고리즘 -  분할 정복: 

https://kimch3617.tistory.com/entry/%EC%95%8C%EA%B3%A0%EB%A6%AC%EC%A6%98-%EB%B6%84%ED%95%A0%EC%A0%95%EB%B3%B5%EB%B2%95-Divide-and-Conquer

https://janghw.tistory.com/entry/%EC%95%8C%EA%B3%A0%EB%A6%AC%EC%A6%98-Divide-and-Conquer-%EB%B6%84%ED%95%A0%EC%A0%95%EB%B3%B5

 

댓글