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 的元素。
比较方便的方法是,每次比较 p->next->val 与 val ,当相等时跳过 p->next 即可: p->next = p->next->next;
ListNode* removeElements(ListNode* head, int val) { ListNode* p = new ListNode();
p->next = head; ListNode* pMake = p; while(p->next != NULL){
if (p->next->val == val){
p->next = p->next->next;
}else{
p = p->next;
}
}
head = pMake->next; return head;
}