Skip to content

Commit a3f69e6

Browse files
committed
merge-two-sorted-lists solution
1 parent 624f908 commit a3f69e6

File tree

1 file changed

+32
-0
lines changed

1 file changed

+32
-0
lines changed
Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
# Definition for singly-linked list.
2+
# class ListNode:
3+
# def __init__(self, val=0, next=None):
4+
# self.val = val
5+
# self.next = next
6+
class Solution:
7+
def mergeTwoLists(self, list1: Optional[ListNode], list2: Optional[ListNode]) -> Optional[ListNode]:
8+
9+
dummy = ListNode(-1) # ๋”๋ฏธ ์‹œ์ž‘ ๋…ธ๋“œ
10+
current = dummy # ํ˜„์žฌ ์—ฐ๊ฒฐ ์œ„์น˜ ํฌ์ธํ„ฐ
11+
12+
while list1 and list2:
13+
14+
# ํ˜„์žฌlist1์˜ ๊ฐ’๊ณผ ํ˜„์žฌlist2๊ฐ’์„ ๋น„๊ตํ•ด์„œ current.next ์—ฐ๊ฒฐ
15+
if list1.val < list2.val:
16+
current.next = list1
17+
list1 = list1.next
18+
else:
19+
current.next = list2
20+
list2 = list2.next
21+
22+
# current ๋‹ค์Œ์œผ๋กœ ์ด๋™
23+
current = current.next
24+
25+
# ๋‘˜ ์ค‘ ํ•˜๋‚˜๊ฐ€ ๋‚จ์•„์žˆ๋‹ค๋ฉด ๋‚˜๋จธ์ง€๋ฅผ ํ†ต์งธ๋กœ ๋ถ™์ด๊ธฐ(์‚ผํ•ญ ์—ฐ์‚ฐ์ž)
26+
current.next = list1 if list1 else list2
27+
# if list1:
28+
# current.next = list1
29+
# else:
30+
# current.next = list2
31+
32+
return dummy.next

0 commit comments

Comments
ย (0)