合并两个有序链表21

题目:将两个有序链表合并为一个新的有序链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。

输入:1->2->4, 1->3->4

输出:1->1->2->3->4->4

思路:与合并两个有序list类似

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
class :
def mergeTwoLists(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
if not l1:
return l2
if not l2:
return l1

# next值),res指针随之改变,l1和l2每次顺次到下一个
res = cur_node = ListNode(0)
while l1 and l2:
if l1.val <= l2.val:
cur_node.next = l1
l1 = l1.next
else:
cur_node.next = l2
l2 = l2.next
cur_node = cur_node.next

if not l1 and l2:
cur_node.next = l2
if not l2 and l1:
cur_node.next = l1
return res.next

例子:

1
2
3
4

l1 = creat_ll([])
l2 = creat_ll([1,3,4])
print_ll(Solution().mergeTwoLists(l1,l2))