Skip to content

Commit 4cc7877

Browse files
author
luzhicheng
committed
更新md
更新md
1 parent 6c39f47 commit 4cc7877

3 files changed

Lines changed: 70 additions & 0 deletions

File tree

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,5 +8,6 @@
88
|[TCP/IP与HTTP协议](./network_protocol/main.md)|网络基础知识,tcp/ip协议与http协议等......|
99
|[LeetCode-数组](./leetcode_array/main.md)|leetcode数组类算法刷题。|
1010
|[LeetCode-栈](./leetcode_stack/main.md)|leetcode栈类算法刷题。|
11+
|[LeetCode-链表](./leetcode_linked_list/main.md)|leetcode链表类算法刷题。|
1112
|[Django学习](./django_note/main.md)|Django学习笔记。|
1213
|[其他](./others/main.md)|redis,kafka,ZeroMQ等|

leetcode_linked_list/main.md

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
## LeetCode链表
2+
1. [合并两个有序链表](合并两个有序链表.md)
Lines changed: 67 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,67 @@
1+
## 合并两个有序链表
2+
将两个升序链表合并为一个新的 升序 链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。
3+
4+
示例:
5+
```python
6+
输入:1->2->4, 1->3->4
7+
输出:1->1->2->3->4->4
8+
```
9+
10+
### 代码
11+
#### 递归
12+
* 如果两个链表有一个是空链表,则返回另一个链表
13+
* 如果两个链表都不是空:
14+
```python
15+
# 两个链表头部值较小的一个节点与剩下元素的 merge 操作结果合并。
16+
l1[0]<=l2[0] l1 = l1[0] + mergeTwoLists(l1[1:], l2)
17+
l1[0]>l2[0] l2 = l2[0] + mergeTwoLists(l1, l2[1:])
18+
```
19+
20+
```python
21+
class ListNode:
22+
def __init__(self, val=0, next=None):
23+
self.val = val
24+
self.next = next
25+
26+
def __str__(self):
27+
var_list = []
28+
var_list.append(self.val)
29+
while self.next:
30+
var_list.append(self.next.val)
31+
self = self.next
32+
return '->'.join([str(item) for item in var_list])
33+
34+
def mergeTwoLists(l1, l2):
35+
if l1 is None:
36+
return l2
37+
elif l2 is None:
38+
return l1
39+
elif l1.val <= l2.val:
40+
l1.next = mergeTwoLists(l1.next, l2)
41+
return l1
42+
elif l1.val > l2.val:
43+
l2.next = mergeTwoLists(l1, l2.next)
44+
return l2
45+
46+
if __name__ == '__main__':
47+
l1 = ListNode(1)
48+
l1.next = ListNode(2)
49+
l1.next.next = ListNode(4)
50+
51+
l2 = ListNode(1)
52+
l2.next = ListNode(3)
53+
l2.next.next = ListNode(4)
54+
print(l1)
55+
print(l2)
56+
res = mergeTwoLists(l1, l2)
57+
print(res)
58+
```
59+
60+
运行结果
61+
```python
62+
1->2->4
63+
1->3->4
64+
1->1->2->3->4->4
65+
```
66+
67+
#### 迭代

0 commit comments

Comments
 (0)