leetcood学习笔记-21**-合并两个有序链表

题目描述:

方法一:

# 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:
        res = ListNode(None)
        node = res
        while l1 and l2:
            if l1.val<l2.val:
                node.next,l1=l1,l1.next
            else:
                node.next,l2=l2,l2.next
            node = node.next
        if l1:
            node.next=l1
        else:
            node.next=l2
        return res.next

方法二:递归

class Solution:
    def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode:
        if l1 is None and l2 is None:
            return None
        if l1 is None:
            return l2
        if l2 is None:
            return l1
        
        if l1.val > l2.val:
            l2.next = self.mergeTwoLists(l1, l2.next)
            return l2
        
        l1.next = self.mergeTwoLists(l1.next, l2)
        return l1

 

python 数据结构之单链表的实现

链接:https://www.cnblogs.com/yupeng/p/3413763.html

posted @ 2019-03-10 20:30  oldby  阅读(155)  评论(0编辑  收藏  举报