# 32ms C++ AC solution

• /**
* struct ListNode {
*     int val;
*     ListNode *next;
*     ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* removeElements(ListNode* head, int val) {
}
while(p->next!=NULL){
if (p->next->val == val){
p->next = p->next->next;
}
else{
p=p->next;
}
}
}
};

• 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) {
}
while(p->next!=NULL){
if (p->next->val == val){
auto freeNode = p->next;
p->next = p->next->next;
free(freeNode);
}
else{
p=p->next;
}
}
}
};

• 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(p) {
if(p->val == val) {
prev->next = p->next;
p = p->next;
} else {
prev = p;
p = p->next;
}
}
}

• @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;

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.