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
알고리즘 - 분할 정복:
'Python > PS in Python' 카테고리의 다른 글
LeetCode 543. Diameter of Binary Tree - Python (0) | 2020.08.25 |
---|---|
LeetCode 121. Best Time to Buy and Sell Stock - Python (0) | 2020.08.24 |
LeetCode 448. Find All Numbers Disappeared in an Array (0) | 2020.08.18 |
LeetCode 283. Move Zeroes - Python (0) | 2020.08.16 |
LeetCode 169. Majority Element - Python (0) | 2020.08.13 |
댓글