-
Notifications
You must be signed in to change notification settings - Fork 3
/
Solution.py
28 lines (22 loc) ยท 1022 Bytes
/
Solution.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
# Definition for singly-linked list.
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class Solution:
def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode:
if None in (l1, l2): # ๋ ์ค ํ๋๊ฐ ์์ผ๋ฉด, ๋ฐ๋ก ๋๋จธ์ง๋ฅผ ๋ฐํํ๋ค.
return l1 or l2
l3 = cur = ListNode(0) # ๋๋ฏธ๋
ธ๋ ์ ์ธ l3๋ ๋จธ๋ฆฌ, cur๋ ํ์ฌ ๋
ธ๋
while l1 and l2: # l1๊ณผ l2๊ฐ ๋ ๋ค ์กด์ฌํ๋ ๋์...
if l1.val < l2.val:
cur.next = l1
l1 = l1.next
else:
cur.next = l2
l2 = l2.next
cur = cur.next
cur.next = l1 or l2 # ๋จ์ ๊ฒ์ ๋ถ์ฌ์ค๋ค.
return l3.next # ๋๋ฏธ๋
ธ๋๋ฅผ ์ ์ธํ ๋
ธ๋๋ฅผ ๋ฐํํ๋ค.
print(Solution.mergeTwoLists(None, ListNode(1, ListNode(2, ListNode(4))), ListNode(1, ListNode(3, ListNode(4)))))
print(Solution.mergeTwoLists(None, ListNode(), ListNode(0)))