Merge Two Sorted Lists - LeetCode
두 개의 정렬된 단방향 연결 리스트가 주어질 때, 두 리스트를 하나의 정렬된 리스트로 합쳐 보자.
우선 입력은 아래와 같다.
# 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, list1: Optional[ListNode], list2: Optional[ListNode]) -> Optional[ListNode]:
list1과 list2를 비교해 더 작은 값을 head로 삼는다. head를 만들 리스트의 기준으로 삼고 순회한다. list1, list2는 각각 기존 리스트 방향을 가리켜야 한다.
예외로 둘 다 빈 리스트라면 빈 리스트를 반환한다. 둘 중 하나가 None이라면 None이 아닌 나머지 리스트를 반환한다.
# 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, list1: Optional[ListNode], list2: Optional[ListNode]) -> Optional[ListNode]:
if list1==None and list2==None:
return None
elif list1==None:
return list2
elif list2==None:
return list1
if list1.val<=list2.val:
head=list1
list1=list1.next
else:
head=list2
list2=list2.next
first=head
while True:
if list1==None:
head.next=list2
break
elif list2==None:
head.next=list1
break
if list1.val<=list2.val:
head.next=list1
head=head.next
list1=list1.next
else:
head.next=list2
head=head.next
list2=list2.next
return first
두 리스트를 순회하면서 새 리스트를 작성하므로 O(2*n)이다.