类型:链表
-
- 移除链表元素 💚
https://leetcode-cn.com/problems/remove-linked-list-elements/
❓ 给你一个链表的头节点 head 和一个整数 val ,请你删除链表中所有满足 Node.val == val 的节点。返回完成删除后的链表结点。
💡 一次遍历
class Solution: def removeElements(self, head: ListNode, val: int) -> ListNode: while head and head.val == val: head = head.next node = head while node: if node.next and node.next.val == val: node.next = node.next.next else: node = node.next return headclass Solution: def removeElements(self, head: ListNode, val: int) -> ListNode: while head and head.val == val: head = head.next slowNode = head while slowNode: if slowNode.next and slowNode.next.val == val: fastNode = slowNode.next while fastNode.next and fastNode.next.val == val: fastNode = fastNode.next slowNode.next = fastNode.next else: slowNode = slowNode.next return head时间复杂度:O(n),空间复杂度:O(1)