File tree Expand file tree Collapse file tree 1 file changed +47
-0
lines changed Expand file tree Collapse file tree 1 file changed +47
-0
lines changed Original file line number Diff line number Diff line change 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
You canโt perform that action at this time.
0 commit comments