题目链接
struct ListNode* removeElements(struct ListNode* head, int val)
{
struct ListNode* cur = head;
struct ListNode* prev=NULL;
while(cur)
{
if(cur->val==val)//删除
{
if(cur==head)//头删处理
{
head = cur->next;
free(cur);
cur = head;
}
else
{
prev->next = cur->next;
free(cur);
cur = prev->next;
}
}
else//向后走
{
prev = cur;
cur = cur->next;
}
}
return head;
}
代码:
struct ListNode* removeElements(struct ListNode* head, int val)
{
struct ListNode* cur = head;
struct ListNode* tail= NULL;
head=NULL;
while(cur)
{
if(cur->val==val)//删除
{
struct ListNode* del = cur;//创建新节点
cur=cur->next;
free(del);
}
else//插入新链表中
{
if(tail==NULL)//第一次插入
{
head=tail=cur;
}
else//后续正常插入
{
tail->next=cur;
tail = tail->next;
}
cur = cur->next;
}
}
if(tail)//尾部置空
{
tail->next=NULL;
}
return head;
}