思路:
用一个新链表来表示合并后的有序链表,
每次比较两个链表,将较小的那个结点存储至新链表中
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution(object):def mergeTwoLists(self, list1, list2):""":type list1: Optional[ListNode]:type list2: Optional[ListNode]:rtype: Optional[ListNode]"""if list1 is None:if list2 is None:return Noneelse:return list2else:if list2 is None:return list1preList =ListNode(0)p = preListwhile list1 and list2:if list1.val<=list2.val:p.next=list1list1=list1.nextelse:p.next=list2list2=list2.nextp =p.nextif list1 is None:p.next=list2else:p.next=list1return preList.next