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
源代码:
/**
* 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 head;
struct ListNode* newhead = head;
while(head != NULL) {
if (head->val == val) {
newhead = head;
head = head->next;
delete newhead;
}
else break;
}
if(head == NULL) return head;
struct ListNode* curr = head;
struct ListNode* n = curr->next;
while(n != NULL) {
if (n->val == val) {
curr->next = n->next;
delete n;
n = curr->next;
}
else {
curr = n;
n = n->next;
}
}
return head;
}
};