203 - Remove Linked List Elements
#easy
Given the head
of a linked list and an integer val
, remove all the nodes of the linked list that has Node.val == val
, and return the new head.
Example 1:
Input: head = [1,2,6,3,4,5,6], val = 6
Output: [1,2,3,4,5]
/**
* 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) {
// head
while ( head != NULL && head -> val == val ) {
if ( head -> next != NULL ) head = head -> next;
else return NULL;
}
ListNode * it = head;
while ( it != NULL ) {
// middle and end; be careful for continued duplicate.
if ( it -> next != NULL && it -> next -> val == val ) {
if ( it -> next -> next != NULL ) {
it -> next = it -> next -> next;
}
else it -> next = NULL;
}
else {
it = it -> next;
}
}
return head;
}
};