Skip to content

Commit faf75ce

Browse files
committed
problem: 0021 merge two sorted lists
1 parent 3cf3e1f commit faf75ce

File tree

2 files changed

+55
-0
lines changed

2 files changed

+55
-0
lines changed
Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
# 0021. Merge Two Sorted Lists
2+
3+
* Difficulty: easy
4+
* Link: https://leetcode.com/problems/merge-two-sorted-lists/
5+
* Topics: Linked-List
6+
7+
# Clarification
8+
9+
1. Check the inputs and outputs
10+
- INPUT: two Linked List
11+
- OUTPUT: one Linked List
12+
13+
# Naive Solution
14+
15+
### Thought Process
16+
17+
- 使用 dummy node
18+
1. 兩個 pointer 分別指向兩個 linked list
19+
2. 將 next 指向 val 較小的那個 Node
20+
- Implement
21+
22+
```python
23+
# Definition for singly-linked list.
24+
# class ListNode:
25+
# def __init__(self, val=0, next=None):
26+
# self.val = val
27+
# self.next = next
28+
class Solution:
29+
def mergeTwoLists(self, list1: Optional[ListNode], list2: Optional[ListNode]) -> Optional[ListNode]:
30+
dummy = ListNode(None)
31+
prev = dummy
32+
while list1 and list2:
33+
if list1.val < list2.val:
34+
prev.next = list1
35+
list1 = list1.next
36+
else:
37+
prev.next = list2
38+
list2 = list2.next
39+
prev = prev.next
40+
41+
if list1:
42+
prev.next = list1
43+
if list2:
44+
prev.next = list2
45+
return dummy.next
46+
```
47+
48+
49+
### Complexity
50+
51+
- Time complexity:$O(n)$
52+
53+
![Untitled](./Untitled.png)
54+
55+
- Space complexity:$O(1)$
40.9 KB
Loading

0 commit comments

Comments
 (0)