mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-08 16:54:50 +08:00
Update 0203.移除链表元素.md
This commit is contained in:
@ -307,21 +307,27 @@ public ListNode removeElements(ListNode head, int val) {
|
|||||||
Python:
|
Python:
|
||||||
|
|
||||||
```python
|
```python
|
||||||
|
(版本一)虚拟头节点法
|
||||||
# Definition for singly-linked list.
|
# Definition for singly-linked list.
|
||||||
# class ListNode:
|
# class ListNode:
|
||||||
# def __init__(self, val=0, next=None):
|
# def __init__(self, val=0, next=None):
|
||||||
# self.val = val
|
# self.val = val
|
||||||
# self.next = next
|
# self.next = next
|
||||||
class Solution:
|
class Solution:
|
||||||
def removeElements(self, head: ListNode, val: int) -> ListNode:
|
def removeElements(self, head: Optional[ListNode], val: int) -> Optional[ListNode]:
|
||||||
dummy_head = ListNode(next=head) #添加一个虚拟节点
|
# 创建虚拟头部节点以简化删除过程
|
||||||
cur = dummy_head
|
dummy_head = ListNode(next = head)
|
||||||
while cur.next:
|
|
||||||
if cur.next.val == val:
|
# 遍历列表并删除值为val的节点
|
||||||
cur.next = cur.next.next #删除cur.next节点
|
current = dummy_head
|
||||||
|
while current.next:
|
||||||
|
if current.next.val == val:
|
||||||
|
current.next = current.next.next
|
||||||
else:
|
else:
|
||||||
cur = cur.next
|
current = current.next
|
||||||
|
|
||||||
return dummy_head.next
|
return dummy_head.next
|
||||||
|
|
||||||
```
|
```
|
||||||
|
|
||||||
Go:
|
Go:
|
||||||
|
Reference in New Issue
Block a user