File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change 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等|
Original file line number Diff line number Diff line change 1+ ## LeetCode链表
2+ 1 . [ 合并两个有序链表] ( 合并两个有序链表.md )
Original file line number Diff line number Diff line change 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+ #### 迭代
You can’t perform that action at this time.
0 commit comments