주어진 list1, list2 의 값들을 앞에서부터 차례대로 비교한다.
두 값 중 더 작은 값을 ListNode 에 넣고, 작은 값이 넣어진 list 를 next 로 옮긴다.
두 list 중 하나라도 None 인 경우, 비교를 위한 반복문이 멈춘다.
반복문을 빠져나온 후에도 아직 값이 남아있는 list 가 있다면, 반환할 ListNode 뒤에 남은 list 를 모두 덧붙여준다.
class Solution:
def mergeTwoLists(self, list1: Optional[ListNode], list2: Optional[ListNode]) -> Optional[ListNode]:
if(list1 is None): return list2
l1 = list1
l2 = list2
result = ml = ListNode()
while(l1 is not None and l2 is not None):
if(l1.val < l2.val):
ml.val = l1.val
l1 = l1.next
else:
ml.val = l2.val
l2 = l2.next
ml.next = ListNode()
ml = ml.next
if(l1 is not None):
ml.val = l1.val
ml.next = l1.next
if(l2 is not None):
ml.val = l2.val
ml.next = l2.next
return result
# 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 is None): return list2
if(list2 is None): return list1
if(list1.val<list2.val) :
root = list1
list1 = list1.next
else :
root = list2
list2 = list2.next
l = root
while list1 is not None and list2 is not None:
if(list1.val<list2.val) :
l.next = list1
list1 = list1.next
else :
l.next = list2
list2 = list2.next
l = l.next
if(list1 is not None):
l.next = list1
elif(list2 is not None):
l.next = list2
return root
< English (feedback by ChatGPT) >
We will compare the two values of the given list1, list2 from the beginning.
(We compare the values of list1 and list2 one by one from the beginning.)
Assign the smaller value between them into ListNode, and move its next of the list which is assigned.
(At each step, we insert the smaller value into a new ListNode, and move forward in the list from which the smaller value was taken.)
If one of the two lists is equals to None, the while loop for comparison is stopped.
(The loop continues until one of the lists becomes None.)
After loop is stopped, if one of the two lists has values left, append all the left to ListNode which will be returned.
(After the loop ends, if any elements remain in either list, we append the remaining nodes to the end of the result ListNode.)
'Coding Interview' 카테고리의 다른 글
| [leetcode] 100. Same Tree (0) | 2025.05.05 |
|---|---|
| [leetcode] 70. Climbing Stairs (0) | 2025.05.05 |
| [leetcode] 26. Remove Duplicates from Sorted Array (0) | 2025.05.01 |
| [leetcode] 20. Valid Parentheses (0) | 2025.05.01 |
| [leetcode] 14. Longest Common Prefix (1) | 2025.05.01 |