# 32ms C++ AC solution

• ``````/**
* Definition for singly-linked list.
* struct ListNode {
*     int val;
*     ListNode *next;
*     ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* removeElements(ListNode* head, int val) {
if (head==NULL){
return head;
}
ListNode* p=head;
while(p->next!=NULL){
if (p->next->val == val){
p->next = p->next->next;
}
else{
p=p->next;
}
}
if (head->val==val)
head=head->next;
return head;
}
};``````

• very nice, better than the ListNode ** version, especially when the data member val is not trivial as an int.

• Don't we need to free the removed ListNodes?

• yes, we do. I forget about that. I should do it after "p->next = p->next->next;"

• ``````class Solution {
public:
ListNode* removeElements(ListNode* head, int val) {
if (head==NULL){
return head;
}
ListNode* p=head;
while(p->next!=NULL){
if (p->next->val == val){
auto freeNode = p->next;
p->next = p->next->next;
free(freeNode);
}
else{
p=p->next;
}
}
if (head->val==val)
head=head->next;
return head;
}
};``````

• Hi, nice code! I just want to know what does AC mean? Is it some sort of algorithm name?
Thanks

• It means accept.

• @TarzanNJane
Abbreviation of accept

• share my solution similar to yours;

``````ListNode* removeElements(ListNode* head, int val) {
while(head && head->val == val) head = head->next;
if(head == nullptr)    return nullptr;

ListNode *p = head->next;
ListNode *prev = head;
while(p) {
if(p->val == val) {
prev->next = p->next;
p = p->next;
} else {
prev = p;
p = p->next;
}
}
return head;
}
``````

• @benyin You're forgetting a free on your very last conditional before you return. In the case where the head has the `val` you want to skip over it but also free the old head right?

• My code:

``````class Solution {
public:
ListNode* removeElements(ListNode* head, int val) {
auto vir = new ListNode(0),
p = vir;
vir->next = head;

while (p->next != NULL) {
auto t = p->next;
if (t->val == val) {
p->next = t->next;
delete t;
} else {
p = p->next;
}
}
return vir->next;
}
};
``````

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.