Skip to content

Commit d5b1d54

Browse files
committed
add week 4 merge-two-sorted-lists
1 parent 03ded85 commit d5b1d54

File tree

1 file changed

+53
-0
lines changed

1 file changed

+53
-0
lines changed

โ€Žmerge-two-sorted-lists/rivkode.py

Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
class ListNode(object):
2+
def __init__(self, val=0, next=None):
3+
self.val = val
4+
self.next = next
5+
6+
class Solution(object):
7+
def mergeTwoLists(self, list1, list2):
8+
"""
9+
:type list1: Optional[ListNode]
10+
:type list2: Optional[ListNode]
11+
:rtype: Optional[ListNode]
12+
"""
13+
# ๋”๋ฏธ ๋…ธ๋“œ ์ƒ์„ฑ
14+
dummy = ListNode(-1)
15+
current = dummy
16+
17+
# ๋‘ ๋ฆฌ์ŠคํŠธ๋ฅผ ์ˆœํšŒํ•˜๋ฉฐ ๋ณ‘ํ•ฉ
18+
while list1 and list2:
19+
if list1.val <= list2.val:
20+
current.next = list1
21+
list1 = list1.next
22+
else:
23+
current.next = list2
24+
list2 = list2.next
25+
current = current.next
26+
27+
# ๋‚จ์•„ ์žˆ๋Š” ๋…ธ๋“œ ์ฒ˜๋ฆฌ
28+
if list1:
29+
current.next = list1
30+
elif list2:
31+
current.next = list2
32+
33+
# ๋”๋ฏธ ๋…ธ๋“œ ๋‹ค์Œ๋ถ€ํ„ฐ ์‹œ์ž‘
34+
return dummy.next
35+
36+
if __name__ == "__main__":
37+
solution = Solution()
38+
39+
# test case
40+
list1 = ListNode(1, ListNode(2, ListNode(4, )))
41+
list2 = ListNode(1, ListNode(3, ListNode(4, )))
42+
43+
result = solution.mergeTwoLists(list1, list2)
44+
45+
while result is not None:
46+
print(result.val)
47+
result = result.next
48+
49+
50+
51+
52+
53+

0 commit comments

Comments
ย (0)