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
1、因为可能有表头是val的情况,设置辅助头结点 Head->next=head,
2、直接在链表中考虑,头结点移动,直到不是val时再进行判断
/**
* 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* Head=new ListNode(-1);
Head->next=head;
ListNode* cur=Head;
while(cur->next!=NULL && cur!=NULL)
{
if(cur->next->val==val)
{
cur->next=cur->next->next;
}
else
{
cur=cur->next;
}
}
return Head->next;
}
};
/**
* 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 NULL;
ListNode* cur=head;
while(cur->val==val)
{
cur=cur->next;
if(cur==NULL)
return NULL;
}
head=cur;
ListNode* temp=head;
while(temp->next!=NULL)
{
if(temp->next->val==val)
{
temp->next=temp->next->next;
}
else
{
temp=temp->next;
}
}
return head;
}
};