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

示例:

输入:1->2->4, 1->3->4
输出:1->1->2->3->4->4



class ListNode:
    def __init__(self, x):
        self.val = x
        self.next = None

    def __repr__(self):# 显示方式
        return "{}->{}".format(self.val,self.next)


class Solution:
    def mergeTwoLists(self, l1, l2):
        """
        :type l1: ListNode
        :type l2: ListNode
        :rtype: ListNode
        """
        if not l1:return l2
        if not l2:return l1
        current =tmp= ListNode(0) #current 和 tmp 指向同一个头结点
        while l1 and l2:
            if l1.val < l2.val:
                current.next = l1
                l1=l1.next
            else:
                current.next = l2
                l2=l2.next

            current = current.next #单向链表,指向最后一个结点"指针"

        current.next = l1 or l2 #current链表最后一个结点的"指针"指向l1或者l2的头结点
        return tmp.next  #current的指针指向了l1或者l2的头结点,返回tmp完整链表

 

内容来源于网络如有侵权请私信删除
你还没有登录,请先登录注册
  • 还没有人评论,欢迎说说您的想法!