Problem:
Remove all elements from a linked list of integers that have value val.
Example
Given: 1 --> 2 --> 6 --> 3 --> 4 --> 5 --> 6, val = 6
Return: 1 --> 2 --> 3 --> 4 --> 5
Analysis:
Solutions:
C++:
ListNode* removeElements(ListNode* head, int val) {
if(head == NULL)
return head;
while(head != NULL && head->val == val) {
ListNode *temp = head;
head = head->next;
temp->next = NULL;
}
if(head == NULL)
return head;
ListNode *front = head->next;
ListNode *back = head;
while(front != NULL) {
if(front->val == val) {
ListNode *temp = front;
back->next = front->next;
front = front->next;
temp->next = NULL;
} else {
back = front;
front = front->next;
}
}
return head;
}
Java
:
Python: