ListNode *removeElements(ListNode *head, int val) {
// O(n)
while (head != NULL && head->val == val) {
head = head->next;
}
ListNode *before = NULL;
ListNode *ptr = head;
ListNode *tmp;
while (ptr != NULL) {
if (ptr->val == val) {
if (before != NULL) {
before->next = ptr->next;
}
// delete ptr and change ptr to ptr->next
tmp = ptr->next;
delete ptr;
ptr = tmp;
} else {
before = ptr;
ptr = ptr->next;
}
}
return head;
}
};
```
These two are taken from discussions, and they are **not** memory safe.
Recursive solution from the same guy:
```cpp
class Solution {
public:
ListNode *removeElements(ListNode *head, int val) {
// Base situation
if (head == NULL)
return NULL;
// Change head->next by it's val (if no val found, will not be changed)
head->next = removeElements(head->next, val);
// Return head or head->next, depending on the val.
// If matched val, return its next, effectively deleting the node.
return (head->val == val) ? head->next : head;
}
};
```
One pointer from [Discussions](https://leetcode.com/problems/remove-linked-list-elements/discuss/722528/C++-2-solutions:-With-single-pointer-+-With-double-pointers-(Easy-to-understand)/1390186)
```cpp
class Solution {
public:
ListNode *removeElements(ListNode *head, int val) {
while (head != NULL && head->val == val)
head = head->next;
// He checked NULL here, so he doesn't have to check in while loop