0
点赞
收藏
分享

微信扫一扫

合并两个有序链表--Python实现

将两个升序链表合并为一个新的 升序 链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:
    def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode:
        head=ListNode(-1)
        tmp=head
        while l1 and l2:
            if l1.val<=l2.val:
                tmp.next=l1
                l1=l1.next
            else:
                tmp.next=l2
                l2=l2.next
            tmp=tmp.next
        tmp.next=l1 if l1 else l2
        return head.next

举报

相关推荐

0 条评论