두 개의 정렬된 목록 A와 B가 있다고 가정합니다. 우리는 그것들을 병합하고 하나의 정렬된 목록 C를 형성해야 합니다. 목록의 크기는 다를 수 있습니다.
예를 들어 A =[1,2,4,7]이고 B =[1,3,4,5,6,8]이라고 가정하면 병합된 목록 C는 [1,1,2,3,4, 4,5,6,7,8]
우리는 재귀를 사용하여 이것을 해결할 것입니다. 따라서 기능은 아래와 같이 작동합니다 -
- merge() 함수의 목록 A와 B를 가정합니다.
- A가 비어 있으면 B를 반환하고 B가 비어 있으면 A를 반환합니다.
- A의 값 <=B의 값이면 A.next =merge(A.next, B) 및 반환 A
- 그렇지 않으면 B.next =merge(A, B.next) 및 B 반환
더 나은 이해를 위해 구현을 살펴보겠습니다.
예제(파이썬)
class ListNode:
def __init__(self, data, next = None):
self.val = data
self.next = next
def make_list(elements):
head = ListNode(elements[0])
for element in elements[1:]:
ptr = head
while ptr.next:
ptr = ptr.next
ptr.next = ListNode(element)
return head
def print_list(head):
ptr = head
print('[', end = "")
while ptr:
print(ptr.val, end = ", ")
ptr = ptr.next
print(']')
class Solution:
def mergeTwoLists(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
if not l1:
return l2
if not l2:
return l1
if(l1.val<=l2.val):
l1.next = self.mergeTwoLists(l1.next,l2)
return l1
else:
l2.next = self.mergeTwoLists(l1,l2.next)
return l2
head1 = make_list([1,2,4,7])
head2 = make_list([1,3,4,5,6,8])
ob1 = Solution()
head3 = ob1.mergeTwoLists(head1,head2)
print_list(head3) 입력
head1 = make_list([1,2,4,7]) head2 = make_list([1,3,4,5,6,8])
출력
[1, 1, 2, 3, 4, 4, 5, 6, 7, 8, ]