题目分析:
这一题是让把两个有序的链表合并成一个有序的链表,可以创建一个新链表,然后比较那两个链表的值逐一添加到新链表就可以了。
代码说明:
1、while(l1 and l2):
,循环比较添加到新链表
2、l_bf.next = l1 if l1 is not None else l2
,某一链表为空跳出循环,这时候只需要把另一不为空的链表添加到l后面即可(l_bf
是l
的尾指针)
3、return l.next
,开始为了方便使新链表的头为-1,所以要从第二节节点返回
测试代码(仅做测试,提交代码在下方):
def print_ListNode(head):
while (True):
print(head.val)
if head.next is not None:
head = head.next
else:
break
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
list_node1_1 = ListNode(1)
list_node1_2 = ListNode(2)
list_node1_3 = ListNode(4)
list_node1_1.next = list_node1_2
list_node1_2.next = list_node1_3
list_node2_1 = ListNode(1)
list_node2_2 = ListNode(3)
list_node2_3 = ListNode(4)
list_node2_1.next = list_node2_2
list_node2_2.next = list_node2_3
class Solution:
def mergeTwoLists(self, l1, l2):
l = ListNode(-1); l_bf = l
while(l1 and l2):
if l1.val < l2.val:
l_bf.next = ListNode(l1.val)
l1 = l1.next
else:
l_bf.next = ListNode(l2.val)
l2 = l2.next
l_bf = l_bf.next
l_bf.next = l1 if l1 is not None else l2
return l.next
print_ListNode(Solution().mergeTwoLists(list_node1_1, list_node2_1)) #提交时强删除该行
提交代码:
class Solution:
def mergeTwoLists(self, l1, l2):
l = ListNode(-1); l_bf = l
while(l1 and l2):
if l1.val < l2.val:
l_bf.next = ListNode(l1.val)
l1 = l1.next
else:
l_bf.next = ListNode(l2.val)
l2 = l2.next
l_bf = l_bf.next
l_bf.next = l1 if l1 is not None else l2
return l.next