Total Accepted: 43183 Total Submissions: 160460 Difficulty: Easy
Remove all elements from a linked list of integers that have value val.
Example
Given: 1 --> 2 --> 6 --> 3 --> 4 --> 5 --> 6, val = 6Return: 1 --> 2 --> 3 --> 4 --> 5/** * 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* p = head,*next=NULL,*pre=NULL; while(p && p->val==val){ next = p->next; delete(p); p = next; head = p; } while(p){ if(p->val == val){ pre->next = p->next; delete(p); p = pre->next; }else{ pre=p; p=p->next; } } return head; }};
Next challenges: