题目:
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的node
思路:
遍历链表,遇到满足要求,就改变next指针的指向。
代码:
ListNode* removeElements(ListNode* head, int val) {
ListNode* l = new ListNode(0);
ListNode* l1 = l;
l->next = head;
while(head)
{
if(head->val == val)
{
l->next = l->next -> next;
}
else
{
l = l -> next;
}
head = head -> next;
}
return l1->next;
}