풀이 1)
# 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]:
dummy_node = ListNode(0)
crnt_node = dummy_node
node1 = list1
node2 = list2
while node1 and node2:
val1 = node1.val
val2 = node2.val
if val1 <= val2:
crnt_node.next = node1
node1 = node1.next
crnt_node = crnt_node.next
else:
crnt_node.next = node2
node2 = node2.next
crnt_node = crnt_node.next
if node1:
crnt_node.next = node1
else:
crnt_node.next = node2
return dummy_node.next
풀이 2)
# 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 not list1 or(list2 and list1 > list2):
list1, list2 = list2, list1
if list1:
list1.next = self.mergeTwoLists(list1.next, list2)
return list1
'자료구조와 알고리즘' 카테고리의 다른 글
2. Add Two Numbers(두 수의 덧셈) (0) | 2023.02.08 |
---|---|
206. Reversed Linked List(역순 연결 리스트) (0) | 2023.02.08 |
234. Palindrome Linked List(팰린드롬 연결 리스트) (0) | 2023.02.05 |
121. Best Time to Buy and Sell Stock(주식을 사고팔기 가장 좋은 시점) (0) | 2023.02.03 |
238. Product of Array Except self(자신을 제외한 배열의 곱) (0) | 2023.02.03 |