zoukankan      html  css  js  c++  java
  • 【Leetcode链表】移除链表元素(203)

    题目

    删除链表中等于给定值 val 的所有节点。

    示例:

    输入: 1->2->6->3->4->5->6, val = 6
    输出: 1->2->3->4->5
    

    解答

    三种方法:

    • 双指针
    • 递归
    • 新开辟一个链表,增加空间复杂度

    通过代码如下:

    # Definition for singly-linked list.
    # class ListNode:
    #     def __init__(self, x):
    #         self.val = x
    #         self.next = None
    
    class Solution:
        # # 方法一:双指针。 时间复杂度O(n),空间复杂度O(1)
        def removeElements(self, head: ListNode, val: int) -> ListNode:
            thead = ListNode(-100)
            thead.next = head
            p, c = thead, head
    
            while c:
                if c.val == val:
                    p.next = c.next
                    c = c.next
                else:
                    p = c
                    c = c.next
            return thead.next
    
        # # 方法三:
        # # 最笨方法,新建一条链表存。时间复杂度O(n),空间复杂度O(n)
        # def removeElements(self, head: ListNode, val: int) -> ListNode:
        #     thead = ListNode(-100)
        #     p = thead
        #     while head:
        #         if head.val != val:
        #             temp = ListNode(head.val)
        #             p.next = temp
        #             p = temp
        #         head = head.next
        #     return thead.next
    
    
        # # 方法二:递归
        # # 回溯时,判断当前节点的值是不是val。 时间复杂度O(n),空间复杂度O(n)
        # def removeElements(self, head: ListNode, val: int) -> ListNode:
        #     if not head:
        #         return head
            
        #     head.next = self.removeElements(head.next, val)
        #     if head.val == val:
        #         return head.next
        #     return head
    
    
    
  • 相关阅读:
    使用Feign访问接口
    IDEA 更改提示一键补全快捷键
    Mac配置Gradle环境
    RestSharp Simple REST and HTTP API Client for .NET
    Vue 一个注册页面有省市联动
    Authentication 接口验证访问 (C#)
    WebService快速入门文档
    自己写了个MongoDB的CRUD文档
    RabbitMQ入门教程
    dubbo简单入门使用
  • 原文地址:https://www.cnblogs.com/ldy-miss/p/11943457.html
Copyright © 2011-2022 走看看