python leetcode21合并两个有序链表
程序员文章站
2022-06-17 19:49:28
...
将两个有序链表合并为一个新的有序链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。
示例:
输入:1->2->4, 1->3->4 输出:1->1->2->3->4->4
python代码
# 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 is None:#l1为空时直接返回l2
return l2
if l2 is None:
return l1
head=ListNode(0)#创建一个新链表,此为头节点
current=head
while l1 is not None and l2 is not None:
if l1.val<l2.val:
current.next=l1
l1=l1.next
else:
current.next=l2
l2=l2.next
current=current.next
if l1 is None:#当l1循环到为空时
current.next=l2
elif l2 is None:
current.next=l1
return head.next####
上一篇: Java ee (八)SpringAOP与动态代理
下一篇: Leetcode - 两数相加