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
思路比较简单,直接遍历,删除就可以了。对于第一个或前多个节点都等于val,直接将head后移,后面出现val则进行链表删除的普通工作
/**
* 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) {
if(head==NULL){
return NULL;
}
ListNode *p=head;
while(p&&p->val==val){
p=p->next;
head=head->next;
}
if(p==NULL){
return head;
}
while(p->next){
if(p->next->val==val){
p->next=p->next->next;
}else{
p=p->next;
}
}
return head;
}
};