Description
Submission
/**
* 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) {
ListNode* prevNode = head;
for(ListNode* node = head; node;) {
if(node->val == val) {
if(head == node) {
head = node = head->next;
} else {
prevNode->next = node = node->next;
}
} else {
prevNode = node;
node = node->next;
}
}
return head;
}
};
Submission 210605
/**
* 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) {
ListNode* dummy = new ListNode(-1, head);
ListNode* prev = dummy;
for(ListNode* ptr = dummy->next; ptr; ptr = ptr->next) {
if(ptr->val == val) {
prev->next = ptr->next;
} else {
prev = ptr;
}
}
return dummy->next;
}
};