Skip to content

Commit 7bd6daa

Browse files
committed
feat: Add Solution to Merge Two Sorted Lists #224
1 parent 36d4ed3 commit 7bd6daa

File tree

1 file changed

+47
-0
lines changed

1 file changed

+47
-0
lines changed
Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
# Definition for singly-linked list.
2+
class ListNode(object):
3+
def __init__(self, val=0, next=None):
4+
self.val = val
5+
self.next = next
6+
7+
class Solution(object):
8+
def mergeTwoLists(self, list1, list2):
9+
"""
10+
:type list1: Optional[ListNode]
11+
:type list2: Optional[ListNode]
12+
:rtype: Optional[ListNode]
13+
- TC: O(m+n)
14+
- SC: O(1)
15+
"""
16+
17+
# ์—ฃ์ง€ ์ผ€์ด์Šค
18+
# ๋‘ ๋ฆฌ์ŠคํŠธ ์ค‘ ํ•˜๋‚˜๋ผ๋„ ๋น„์–ด ์žˆ๋Š” ๊ฒฝ์šฐ,
19+
# ๋‚˜๋จธ์ง€ ๋ฆฌ์ŠคํŠธ ๋ฐ”๋กœ ๋ฐ˜ํ™˜
20+
if not list1:
21+
return list2
22+
if not list2:
23+
return list1
24+
25+
# ๋”๋ฏธ ํ—ค๋“œ ๋…ธ๋“œ
26+
# ๊ฒฐ๊ณผ ๋ฆฌ์ŠคํŠธ ์‹œ์ž‘์  ์—ญํ• ์„ ํ•  ๊ฐ€์งœ ๋…ธ๋“œ ์ƒ์„ฑ
27+
dummy = ListNode()
28+
current = dummy # current๋Š” ํ˜„์žฌ๊นŒ์ง€ ๋งŒ๋“  ๋ฆฌ์ŠคํŠธ์˜ ๋งˆ์ง€๋ง‰ ๋…ธ๋“œ
29+
30+
# ๋‘ ๋ฆฌ์ŠคํŠธ ๋ชจ๋‘ ๋…ธ๋“œ๊ฐ€ ๋‚จ์•„ ์žˆ์„ ๋•Œ๊นŒ์ง€ ๋ฐ˜๋ณต
31+
while list1 and list2:
32+
if list1.val <= list2.val:
33+
current.next = list1
34+
list1 = list1.next
35+
else:
36+
current.next = list2
37+
list2 = list2.next
38+
current = current.next
39+
40+
# ๋‚จ์€ ๋…ธ๋“œ๋“ค ์ด์–ด ๋ถ™์ด๊ธฐ
41+
# ์•„์ง ๋…ธ๋“œ๊ฐ€ ๋‚จ์•„ ์žˆ๋Š” ๋ฆฌ์ŠคํŠธ๊ฐ€ ์žˆ์œผ๋ฉด ํ†ต์งธ๋กœ ๋ถ™์ด๊ธฐ
42+
if list1:
43+
current.next = list1
44+
elif list2:
45+
current.next = list2
46+
47+
return dummy.next

0 commit comments

Comments
ย (0)