题目
删除链表中等于给定值 val 的所有节点。
示例
输入: 1->2->6->3->4->5->6, val = 6
输出: 1->2->3->4->5
C++代码
/**
* 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)
{
while(head!=NULL&&head->val==val) head=head->next; //[1,1] 1
if(head==NULL) return head;
ListNode* dummy=new ListNode(0);
dummy->next=head;
ListNode* tmp=dummy;
while(tmp->next!=NULL)
{
if(tmp->next->val==val) tmp->next=tmp->next->next;
else tmp=tmp->next;
}
return head;
}
};