Skip to content
Merged
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 26 additions & 0 deletions merge-two-sorted-lists/hu6r1s.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
# 시간복잡도: O(n + m) -> 두 리스트의 모든 노드를 한 번씩 방문
# 공간복잡도: O(1) -> 기존 노드 재배치, 추가 메모리 거의 없음
def mergeTwoLists(self, list1: Optional[ListNode], list2: Optional[ListNode]) -> Optional[ListNode]:
merged_list = ListNode()
tail = merged_list

while list1 and list2:
if list1.val < list2.val:
tail.next = list1
list1 = list1.next
else:
tail.next = list2
list2 = list2.next
tail = tail.next

if list1:
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

-> tail.next = list1 if list1 else list2 로 간결히 작성 가능합니다

tail.next = list1
else:
tail.next = list2
return merged_list.next