Leetcode python 21. 合并两个有序链表 203. 移除链表元素


21. 合并两个有序链表

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

img

示例 1:
输入:l1 = [1,2,4], l2 = [1,3,4]
输出:[1,1,2,3,4,4]

示例 2:
输入:l1 = [], l2 = []
输出:[]

示例 3:
输入:l1 = [], l2 = [0]
输出:[0]

class Solution:
    def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode:
        if l1 is None:
            return l2
        elif l2 is 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

执行用时:36 ms, 在所有 Python3 提交中击败了68.33%的用户
内存消耗:15 MB, 在所有 Python3 提交中击败了27.89%的用户

203. 移除链表元素

给你一个链表的头节点 head 和一个整数 val ,请你删除链表中所有满足 Node.val == val 的节点,并返回 新的头节点

img

示例 1: m
输入:head = [1,2,6,3,4,5,6], val = 6
输出:[1,2,3,4,5]

class Solution:
    def removeElements(self, head: ListNode, val: int) -> ListNode:
        if head is None:
            return head
        head.next = self.removeElements(head.next, val)
        if head.val == val:
            next_node = head.next 
        else:
            next_node = head
        return next_node

执行用时:64 ms, 在所有 Python3 提交中击败了44.91%的用户
内存消耗:26.2 MB, 在所有 Python3 提交中击败了5.10%的用户

posted @ 2021-09-21 22:13  HEREISDAVID  阅读(69)  评论(0编辑  收藏  举报