题目描述:将两个升序链表合并为一个新的升序链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。 难度:简单 输入:1->2->4, 1->3->4 输出:1->1->2->3->4->4
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode:
head = ListNode(0)
l3 = head
while l1 and l2:
if l1.val <= l2.val:
l3.next = l1
l1 = l1.next
else:
l3.next = l2
l2 = l2.next
l3 = l3.next
if l1:
l3.next = l1
if l2:
l3.next = l2
return head.next
![3968d4df0124c9d193a145b12ba105ca.png](https://img-blog.csdnimg.cn/img_convert/3968d4df0124c9d193a145b12ba105ca.png)
类型:链表
题目位置 思路分析:其实这个题在数据结构里面有提及,下面这个思路完全一样,python列表简化更容易懂
def mergeTwoLists(l1,l2):
i,j,l3 = 0,0,[]
while i<len(l1) and j<len(l2):
if l1[i] <= l2[j]:
l3.append(l1[i])
i += 1
else:
l3.append(l2[j])
j += 1
if len(l1) == i:
while j<len(l2):
l3.append(l2[j])
j += 1
else:
while i<len(l1):
l3.append(l1[i])
i += 1
return l3
if __name__ == '__main__':
l1 = [1,3,5,7,9]
l2 = [0,2,4,6,8]
print(mergeTwoLists(l1,l2)) #[0,1,2,3,4,5,6,7,8,9]
![b6268c20b08be41bd927489c3f0e740d.png](https://img-blog.csdnimg.cn/img_convert/b6268c20b08be41bd927489c3f0e740d.png)
warning :未经授权,不得转载
有问题的小伙伴请在下方留言,喜欢就点个赞吧;关注我,带你一起写bug
CSDN:带只拖鞋去流浪
简书:带只拖鞋去流浪