题目描述
删除链表中等于给定值 val 的所有节点。
示例:
输入: 1->2->6->3->4->5->6, val = 6
输出: 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;
ListNode *cur = new ListNode(-1);
cur->next =head;
ListNode *s =NULL;
ListNode *H = cur;
while(cur->next != NULL){
if(cur->next->val == val){
s = cur->next;
cur->next = cur->next->next;
delete s;
}else{
cur = cur->next;
}
}
return H->next;
}
};