Skip to content

Commit 666ad79

Browse files
committed
merge-two-sorted-lists solution
1 parent 626fc9f commit 666ad79

File tree

1 file changed

+33
-0
lines changed

1 file changed

+33
-0
lines changed
Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
"""
2+
기억할 키워드
3+
dummy.next 리턴해서 건너뜀
4+
list1 list2 둘 중 하나가 None이 되면 while문 끝내고 나머지 next로 이어줌
5+
6+
list1의 길이 M, list2의 길이N
7+
8+
TC : O(M + N)
9+
10+
SC : O(1)
11+
12+
추가적인 풀이 : 알고달레에서 재귀방법 확인
13+
"""
14+
# Definition for singly-linked list.
15+
# class ListNode:
16+
# def __init__(self, val=0, next=None):
17+
# self.val = val
18+
# self.next = next
19+
class Solution:
20+
def mergeTwoLists(self, list1: Optional[ListNode], list2: Optional[ListNode]) -> Optional[ListNode]:
21+
dummy = ListNode()
22+
node = dummy
23+
24+
while list1 and list2 :
25+
if list1.val < list2.val :
26+
node.next = ListNode(list1.val)
27+
list1 = list1.next
28+
else :
29+
node.next = ListNode(list2.val)
30+
list2 = list2.next
31+
node = node.next
32+
node.next = list1 or list2
33+
return dummy.next

0 commit comments

Comments
 (0)