将两个链表合并后再排序
链表定义:
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
将列表转化为链表:
def create_linked_list(lst):
dummy = ListNode() # 创建一个虚拟头节点
current = dummy # 设置当前节点为虚拟头节点
for number in lst: # 遍历输入的列表
current.next = ListNode(number) # 创建新节点,连接到当前节点的后面
current = current.next # 将当前节点指针移动到下一个节点
return dummy.next # 返回虚拟头节点的下一个节点,即实际的链表头
合并并排序的方法:
class Solution1:
def mergeTwoLists(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
if l1==None and l2==None:
return None
if l1==None:
return l2
if l2==None:
return l1
if l1.val<=l2.val:
l1.next=self.mergeTwoLists(l1.next,l2)
return l1
else:
l2.next=self.mergeTwoLists(l1,l2.next)
return l2
class Solution2:
def mergeTwoLists(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
head = ListNode(0)
first = head
while l1 != None and l2 != None:
if l1.val > l2.val:
head.next = l2
l2 = l2.next
else :
head.next = l1
l1 = l1.next
head = head.next
if l1 == None:
head.next = l2
elif l2 == None:
head.next = l1
return first.next