Skip to content

Commit

Permalink
add merge-two-sorted-lists (#66)
Browse files Browse the repository at this point in the history
  • Loading branch information
AlpherJang authored Aug 18, 2023
1 parent 58201b9 commit 97ed666
Show file tree
Hide file tree
Showing 5 changed files with 48 additions and 5 deletions.
1 change: 1 addition & 0 deletions SUMMARY.md
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,7 @@
* [链表](linked-list/README.md)
* [环形链表](linked-list/linked-list-cycle.md)
* [两数相加](linked-list/liang-shu-xiang-jia.md)
* [合并两个有序链表](linked-list/merge-two-sorted-lists.md)
* [](tree/README.md)
* [二叉树的最大深度](tree/maximum-depth-of-binary-tree.md)
* [](graph/README.md)
Expand Down
4 changes: 2 additions & 2 deletions linked-list/add-two-numbers.md
Original file line number Diff line number Diff line change
Expand Up @@ -41,5 +41,5 @@ func addTwoNumbers(l1 *ListNode, l2 *ListNode) *ListNode {

## 复杂度分析

- **时间复杂度:** 只遍历了一遍字符串,因此时间复杂度为 $$O(n)$$,其中 $$n$$ 是链表的长度
- **空间复杂度:** 只使用了常数个变量,因此空间复杂度为 $$O(n)$$
- **时间复杂度:** 只遍历了一遍链表,因此时间复杂度为 $$O(n)$$,其中 $$n$$ 是链表的长度
- **空间复杂度:** 空间复杂度为 $$O(n)$$
2 changes: 0 additions & 2 deletions linked-list/liang-shu-xiang-jia.md

This file was deleted.

2 changes: 1 addition & 1 deletion linked-list/linked-list-cycle.md
Original file line number Diff line number Diff line change
Expand Up @@ -33,4 +33,4 @@ func hasCycle(head *ListNode) bool {
## 复杂度分析

- **时间复杂度:** 只遍历了一遍字符串,因此时间复杂度为 $$O(n)$$,其中 $$n$$ 是链表的长度
- **空间复杂度:** 只使用了常数个变量,因此空间复杂度为 $$O(n)$$
- **空间复杂度:** 空间复杂度为 $$O(n)$$
44 changes: 44 additions & 0 deletions linked-list/merge-two-sorted-lists.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
# 合并两个有序链表

题目链接: [https://leetcode.cn/problems/merge-two-sorted-lists](https://leetcode.cn/problems/merge-two-sorted-lists)

## 解题思路:

1. 同时遍历两个链表,判断哪个链表的元素小,小的元素入结果链表中,并将结果链表以及小的元素所在链表指针均向后移一位
2. 若某一链表为空,则将另一个链表剩余的元素一并合并到结果链表zhong


```go
/**
* Definition for singly-linked list.
* type ListNode struct {
* Val int
* Next *ListNode
* }
*/
func mergeTwoLists(list1 *ListNode, list2 *ListNode) *ListNode {
res:=new(ListNode)
head:=res
for list1!=nil&&list2!=nil{
if list1.Val>list2.Val{
head.Next=list2
list2=list2.Next
}else{
head.Next=list1
list1=list1.Next
}
head=head.Next
}
if list1==nil{
head.Next=list2
}else{
head.Next=list1
}
return res.Next
}
```

## 复杂度分析

- **时间复杂度:** 只遍历了一遍链表,因此时间复杂度为 $$O(n)$$,其中 $$n$$ 是链表的长度
- **空间复杂度:** 空间复杂度为 $$O(n)$$

0 comments on commit 97ed666

Please sign in to comment.