# 203. Remove Linked List Elements

**<font color=red>难度: Easy</font>**

## 刷题内容

> 原题连接

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

> 内容描述

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

Example:

Input:  1->2->6->3->4->5->6, val = 6
Output: 1->2->3->4->5
```

## 解题方案

> 思路 1
******- 时间复杂度: O(N)******- 空间复杂度: O(1)******


最简单的方式，直接遍历，值等于val的点直接跳过, beats 100%

这个方式最好了


```python
class Solution:
    def removeElements(self, head, val):
        """
        :type head: ListNode
        :type val: int
        :rtype: ListNode
        """
        cur = dummy = ListNode(-1)
        while head:
            if head.val != val:
                cur.next = head
                cur = cur.next
            head = head.next
        cur.next = None
        return dummy.next
```

> 思路 2
******- 时间复杂度: O(N)******- 空间复杂度: O(1)******

迭代，beats 100%

```python
class Solution:
    def removeElements(self, head, val):
        """
        :type head: ListNode
        :type val: int
        :rtype: ListNode
        """
        while head and head.val == val:
            head = head.next
        if not head:
            return head
        prev = head
        while prev.next:
            if prev.next.val == val:
                prev.next = prev.next.next
            else:
                prev = prev.next
        return head
```

> 思路 3
******- 时间复杂度: O(N)******- 空间复杂度: O(1)******


递归, beats 49.16%

```python
class Solution:
    def removeElements(self, head, val):
        """
        :type head: ListNode
        :type val: int
        :rtype: ListNode
        """
        if not head:
            return head
        head.next = self.removeElements(head.next, val)
        return head if head.val != val else head.next
```
