# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def mergeTwoLists(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
if l1 == None:
if l2 == None:
return None
else:
return l2
elif l2 == None:
return l1
prehead = ListNode(None)
tmp = prehead
while l1 != None and l2 != None:
if l1.val < l2.val:
tmp.next = l1
tmp = l1
l1 = l1.next
else:
tmp.next = l2
tmp = l2
l2 = l2.next
if l1 == None:
tmp.next = l2
elif l2 == None:
tmp.next = l1
return prehead.next
Python, LeetCode, 21. 合并两个有序链表
最新推荐文章于 2024-03-09 11:29:59 发布