Give you a list of the head node head And an integer val , Please delete all the contents in the linked list Node.val == val The node of , And back to New head node .
Example 1:
Input :head = [1,2,6,3,4,5,6], val = 6
Output :[1,2,3,4,5]
Example 2:
Input :head = [], val = 1
Output :[]
Example 3:
Input :head = [7,7,7,7], val = 7
Output :[]
Tips :
The nodes in the list are in range [0, 104] Inside
1 <= Node.val <= 50
0 <= k <= 50
/**
* 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 *p,*pre;
while(head&&head->val==val)
{
p = head;
head = head->next;
// del p;
}
if(head==nullptr) return head;
p = head->next;
pre = head;
while(p)
{
if(p->val==val)
{
pre->next = p->next;
p = pre->next;
// del()
}
else{
pre = p;
p = p->next;
}
}
return head;
}
};