Skip to content

Commit 2dccaf5

Browse files
committed
solve merge two sorted list
1 parent 74c8ccc commit 2dccaf5

1 file changed

Lines changed: 26 additions & 0 deletions

File tree

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
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+
์‹œ๊ฐ„๋ณต์žก๋„: O(n)
10+
๊ณต๊ฐ„๋ณต์žก๋„: O(1)
11+
1. ๋‘ ๋ฆฌ์ŠคํŠธ๋ฅผ ํ•ฉ์ณ์„œ ์ƒˆ๋กœ์šด ๋ฆฌ์ŠคํŠธ ๋ฐ˜ํ™˜
12+
2. ๋‘ ๋ฆฌ์ŠคํŠธ๋ฅผ ๋Œ๋ฉด์„œ ์ž‘์€ ๊ฐ’์„ ์ƒˆ๋กœ์šด ๋ฆฌ์ŠคํŠธ์— ์ถ”๊ฐ€
13+
3. ๋‘ ๋ฆฌ์ŠคํŠธ๋ฅผ ๋ชจ๋‘ ์ˆœํšŒํ•˜๋ฉด ๋‚จ์€ ๊ฒƒ์„ ์ƒˆ๋กœ์šด ๋ฆฌ์ŠคํŠธ์— ์ถ”๊ฐ€
14+
"""
15+
root = ListNode(None)
16+
node = root
17+
while list1 and list2:
18+
if list1.val < list2.val:
19+
node.next = list1
20+
list1 = list1.next
21+
else:
22+
node.next = list2
23+
list2 = list2.next
24+
node = node.next
25+
node.next = list1 or list2
26+
return root.next

0 commit comments

Comments
ย (0)