forked from itcharge/LeetCode-Py
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
2 changed files
with
46 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -127,3 +127,6 @@ dmypy.json | |
|
||
# Pyre type checker | ||
.pyre/ | ||
|
||
# Custom | ||
Temp |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,43 @@ | ||
#### [0021. 合并两个有序链表](https://leetcode-cn.com/problems/merge-two-sorted-lists/) | ||
|
||
- 标签:链表 | ||
- 关键词: | ||
|
||
## 题目大意 | ||
|
||
给定两个升序链表,将其合并为一个升序链表。 | ||
|
||
## 解题思路 | ||
|
||
利用归并排序的思想。 | ||
|
||
创建一个新的链表节点作为头结点(记得保存),然后判断 l1和 l2 头结点的值,将较小值的节点添加到新的链表中。 | ||
|
||
当一个结点添加到新的链表中之后,将对应的 l1 或 l2 链表向后移动一位。 | ||
|
||
然后继续判断当前 l1 结点和当前 l2 结点的值,继续将较小值的节点添加到新的链表中,然后将对应的链表向后移动一位。 | ||
|
||
这样,当 l1 或 l2 遍历到最后,最多有一个链表还有节点未遍历,则直接将该结点链接到新的链表尾部即可。 | ||
|
||
## 代码 | ||
|
||
```Python | ||
class Solution: | ||
def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode: | ||
newHead = ListNode(-1) | ||
|
||
curr = newHead | ||
while l1 and l2: | ||
if l1.val <= l2.val: | ||
curr.next = l1 | ||
l1 = l1.next | ||
else: | ||
curr.next = l2 | ||
l2 = l2.next | ||
curr = curr.next | ||
|
||
curr.next = l1 if l1 is not None else l2 | ||
|
||
return newHead.next | ||
``` | ||
|