21. 合并两个有序链表

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

  • 示例 1:
    输入:l1 = [1,2,4], l2 = [1,3,4]
    输出:[1,1,2,3,4,4]
  • 示例 3:
    输入:l1 = [], l2 = [0]
    输出:[0]
点击查看提交代码
class Solution:
    def mergeTwoLists(self,l1, l2):
        if not l1: return l2  # 终止条件,直到两个链表都空
        if not l2: return l1
        if l1.val <= l2.val:  # 递归调用
            l1.next = self.mergeTwoLists(l1.next,l2)
            return l1
        else:
            l2.next = self.mergeTwoLists(l1,l2.next)
            return l2
点击查看所有pycharm的代码
class ListNode:
    def __init__(self, val=0, next=None):
        self.val = val
        self.next = next

    @classmethod
    def from_list(cls, lst):
        """Create a linked list from a Python list"""
        # Create a linked list from the values in the input list, in order
        head = None
        for val in reversed(lst):
            head = ListNode(val=val, next=head)

        return head

    def to_list(self):
        """Convert the linked list to a Python list"""
        # Create a Python list from the values in the linked list, in order
        lst = []
        node = self
        while node is not None:
            lst.append(node.val)
            node = node.next

        return lst

class Solution:
    def mergeTwoLists(self,l1, l2):
        if not l1: return l2  # 终止条件,直到两个链表都空
        if not l2: return l1
        if l1.val <= l2.val:  # 递归调用
            l1.next = self.mergeTwoLists(l1.next,l2)
            return l1
        else:
            l2.next = self.mergeTwoLists(l1,l2.next)
            return l2
if __name__ == '__main__':
    # solution = Solution()
    # l1 = [1, 2, 4]错了,是链表不是列表
    # l2 = [1, 3, 4]
    # print(solution.mergeTwoLists(l1, l2))

    # Create two linked lists from the input lists
    l1 = ListNode.from_list([1, 2, 4])
    l2 = ListNode.from_list([1, 3, 4])
    solution = Solution()
    # Merge the two linked lists
    merged = solution.mergeTwoLists( l1, l2)
    # Print the merged linked list
    print(merged.to_list())
posted @ 2022-12-12 15:57  辛宣  阅读(29)  评论(0)    收藏  举报