"""
Definition of ListNode
class ListNode(object):
def __init__(self, val, next=None):
self.val = val
self.next = next
"""
class Solution:
"""
@param l1: ListNode l1 is the head of the linked list
@param l2: ListNode l2 is the head of the linked list
@return: ListNode head of linked list
"""
def mergeTwoLists(self, l1, l2):
# write your code here
#初始化一个新的链表,循环,比较l1.val 和 l2.val的大小。最后,如果那个链表没有取完,则直接丢进来
#初始化一个新的链表
dummay = ListNode(0) #如果不重新赋值tail尾巴的话,dummy一直在往后面链接新的节点,但是最终需要返回的是第一个节点的next,所以需要一个尾巴在后面不停的链接新节点,不停的更新指向
tail = dummay
while l1 and l2:
if l1.val < l2.val:
#每一个赋予一个新的节点
tail.next = ListNode(l1.val)
l1 = l1.next
else:
tail.next = ListNode(l2.val)
l2 = l2.next
tail = tail.next
#最后,如果还剩下l1,或者l2
if l1:
tail.next = l1
else:
tail.next = l2
return dummay.next