leetcode 21 链表合并

方法一:

class Solution:
    def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode:
        p1=l1
        p2=l2
        prehead=ListNode(-1)
        #ListNode{val:-1,next:None}
        cur=prehead
        while p1 and p2:
            if p1.val > p2.val:
                cur.next=p2
                p2=p2.next
            else:
                cur.next=p1
                p1=p1.next
            cur=cur.next
        cur.next = p1 if p1!=None else p2

        return prehead.next

方法二:
递归调用一定要用 self 调用

#递归法
class Solution:
    def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode:
        if l1==None:
            return l2
        elif l2==None:
            return l1
        elif l1.val < l2.val:
            l1.next = self.mergeTwoLists(l1.next,l2)
            return l1
        else :
            l2.next = self.mergeTwoLists(l1,l2.next)
            return l2
发布了16 篇原创文章 · 获赞 3 · 访问量 1071

猜你喜欢

转载自blog.csdn.net/weixin_39666736/article/details/104060548