# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution(object):
def removeElements(self, head, val):
"""
:type head: ListNode
:type val: int
:rtype: ListNode
"""
# 1.迭代
if head is None:
return
# 找到首个值不为val的节点
while head is not None:
if head.val != val:
break
head = head.next
pre = head
cur = head
while cur is not None:
if cur.val == val:
pre.next = cur.next
else:
pre = cur
cur = cur.next
return head
# 2.递归
if head is None:
return head
head.next = self.removeElements(head.next, val)
return head.next if head.val == val else head
70-Linkedlist--LC203移除链表元素
最新推荐文章于 2025-07-23 09:00:03 发布