leetcode 203. remove-linked-list-elements 移除链表元素 python3

时间:2020-6-3

题目地址:https://leetcode-cn.com/problems/remove-linked-list-elements/

题目难度:Easy

题目描述:

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

示例:

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

思路1:遍历链表节点,针对头节点写特殊逻辑

代码段1:通过

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:
    def removeElements(self, head: ListNode, val: int) -> ListNode:
        if head == None:
            return None
        if head.next == None:
            if head.val == val:
                return None
            else:
                return head
        while head != None and head.val == val:
            start = head.next
            head = head.next
        if head != None and head.val != val:
            start = head   
        while(head != None and head.next != None):
            if head.next.val == val:
                if head.next.next != None:
                    head.next = head.next.next
                else:
                    head.next = None
            else:
                head.next = head.next
                head = head.next
        return start

总结:

  1. 我写的逻辑冗余且混乱,看下别人放的代码
# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:
    def removeElements(self, head: ListNode, val: int) -> ListNode:
        # 链表为空
        if head == None:
            return None
        # 头节点的特殊逻辑
        while head != None and head.val == val:
            head = head.next
        start = head 
        # 处理节点  
        while(start != None and start.next != None):
            if start.next.val == val:
                    start.next = start.next.next
            else:
                start = start.next
        return head

思路2:遍历链表节点,针对头节点写特殊逻辑

官方的算法题解写的很清楚啊,我也需要多练习

代码段2:通过

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:
    def removeElements(self, head: ListNode, val: int) -> ListNode:
        sentinel = ListNode(0)
        sentinel.next = head
        prev, curr = sentinel, head
        while(curr):
            if(curr.val == val):
                prev.next = curr.next
            else:
                prev = curr
            curr = curr.next
        return sentinel.next

总结:

  1. 哨兵节点广泛应用于树和链表中,如伪头、伪尾、标记等,它们是纯功能的,通常不保存任何数据,其主要目的是使链表标准化,如使链表永不为空、永不无头、简化插入和删除。
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值