Skip to content

Commit

Permalink
Add: 0021. 合并两个有序链表
Browse files Browse the repository at this point in the history
  • Loading branch information
itcharge committed Apr 1, 2021
1 parent 9d7df1f commit c3610b0
Show file tree
Hide file tree
Showing 2 changed files with 46 additions and 0 deletions.
3 changes: 3 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -127,3 +127,6 @@ dmypy.json

# Pyre type checker
.pyre/

# Custom
Temp
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
```

0 comments on commit c3610b0

Please sign in to comment.