思路:
用一个新链表来表示合并后的有序链表,
每次比较两个链表,将较小的那个结点存储至新链表中
# 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 None
else:
return list2
else:
if list2 is None:
return list1
preList =ListNode(0)
p = preList
while list1 and list2:
if list1.val<=list2.val:
p.next=list1
list1=list1.next
else:
p.next=list2
list2=list2.next
p =p.next
if list1 is None:
p.next=list2
else:
p.next=list1
return preList.next