# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def mergeTwoLists(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
res = ListNode(0)
# head = ListNode(0)
pre = res
while l1 and l2 :
if l1.val <= l2.val:
pre.next, l1 = l1, l1.next
else:
pre.next, l2 = l2, l2.next
pre = pre.next
if l1 is not None:
pre.next = l1
if l2 is not None:
pre.next = l2
return res.next
在循环内部,如果l1.val <= l2.val就xx,后面如果写 l2.val < l1.val,就会报错说l2是nonetype,没有val这个属性,换成else就可以正常运行,我在想可能是因为如果是if else说明在这一轮判断中只会选择其中一种情况来进行连接,而如果是if if则会进行两次判断连接