From: https://leetcode.com/problems/remove-linked-list-elements/
-------------------------------------
Question:
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
Solution: Add a node head so that removing the head will be easier.
/**
* 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* pHead = new ListNode(0);
pHead->next = head;
ListNode* pre=pHead, *cur=head, *temp;
while(cur) {
if(cur->val == val) {
temp = cur;
cur=cur->next;
pre->next = cur;
delete temp;
} else {
pre=cur;
cur=cur->next;
}
}
temp = pHead->next;
delete pHead;
return temp;
}
};