Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
/*
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
ListNode* removeElements(ListNode* head, int val) {
if(head==NULL)
return head;
while(head!=NULL && head->val==val)
{
head=head->next;
}
if(head==NULL || head->next==NULL)
return head;
ListNode *prev=head;
ListNode *p=head->next;
while(p!=NULL)
{
if(p->val==val)
{
prev->next=p->next;
p=p->next;
}
else
{
prev=p;
p=p->next;
}
}
return head;
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment