删除链表中等于给定值val的所有节点。
给出链表 1->2->3->3->4->5->3, 和 val = 3, 你需要返回删除3之后的链表:1->2->4->5。
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
/**
* @param head a ListNode
* @param val an integer
* @return a ListNode
*/
ListNode *removeElements(ListNode *head, int val) {
if(head==NULL ) return NULL;
ListNode *pre,*p,*post;
ListNode *hh=new ListNode(INT_MAX);
hh->next=head;//头上加头,不用考虑链表换头
for(pre=p=hh;p!=NULL;p=p->next ){
if(p->val==val){
pre->next=p->next;
p=pre;//重复的1-1,要判断重复判读
}
pre=p;
}
return hh->next;
}
};