203. Remove Linked List Elements [easy] (Python)

这篇博客讨论了LeetCode上的第203题,即如何删除单链表中值为给定值的节点。提供了两种解决方案:一种是遍历链表并使用伪头节点删除节点,另一种是通过快慢指针更新链表节点值。此外,还提到了一个尝试使用递归但未能通过测试的解法。

题目链接

https://leetcode.com/problems/remove-linked-list-elements/

题目原文

Remove all elements from a linked list of integers that have value val.

Example
Given: 1 –> 2 –> 6 –> 3 –> 4 –> 5 –> 6, val = 6
Return: 1 –> 2 –> 3 –> 4 –> 5

题目翻译

删除单链表中值为给定的val的节点。比如:给定链表 1 –> 2 –> 6 –> 3 –> 4 –> 5 –> 6 和值 val = 6 ,返回 1 –> 2 –> 3 –> 4 –> 5 。

思路方法

思路一

遍历所有节点,同时保留每个节点的上一个节点,当遇到节点值是val时,删除该节点。为了方便操作,定义了一个伪头节点。

代码

# Definition for singly-linked list.
# class ListNode(object):
#     def __init__(s
### 双向链表的Python实现 #### 定义结点类 为了创建双向链表,首先需要定义一个`Node`类来表示单个节点。每个节点包含三个属性:存储的数据(`data`)、指向下一个节点的指针(`next`)以及指向前一个节点的指针(`prev`)。 ```python class Node: def __init__(self, data=None): self.data = data self.next = None self.prev = None ``` #### 定义链表类 接着定义`DoublyLinkedList`类用于管理这些节点并提供操作接口。初始化方法设置头部和尾部为空,并维护列表大小计数器。 ```python class DoublyLinkedList: def __init__(self): self.head = None self.tail = None self.size = 0 ``` #### 插入新节点的方法 可以在链表的不同位置插入新的节点,这里展示两种常见的插入方式: ##### 头插法 在链表开头添加一个新的节点作为新的头节点。 ```python def add_first(self, value): new_node = Node(value) if not self.head: self.head = self.tail = new_node else: new_node.next = self.head self.head.prev = new_node self.head = new_node self.size += 1 ``` ##### 尾插法 在链表结尾处追加一个新节点成为新的尾节点。 ```python def add_last(self, value): new_node = Node(value) if not self.tail: self.head = self.tail = new_node else: new_node.prev = self.tail self.tail.next = new_node self.tail = new_node self.size += 1 ``` #### 删除指定值的第一个匹配项 此功能允许移除首次出现的目标元素对应的节点。 ```python def remove(self, target_value): current = self.head while current and current.data != target_value: current = current.next if not current: return False # Not found if current.prev is None: self.head = current.next else: current.prev.next = current.next if current.next is None: self.tail = current.prev else: current.next.prev = current.prev self.size -= 1 return True ``` 以上实现了基本的双向链表结构及其核心增删改查的功能[^4]。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值