给你一个链表的头节点 head
和一个整数 val
,请你删除链表中所有满足 Node.val == val
的节点,并返回 新的头节点 。
方法一:常规做。但是需要先判断头节点是否需要删除
cpp
class Solution
{
public:
ListNode* removeElements(ListNode* head, int val)
{
while(head!=nullptr&&head->val==val)
{
ListNode*tmp=head;
head=head->next;
delete tmp;
}
ListNode*cur=head;
while(cur!=nullptr&&cur->next!=nullptr)
{
if(cur->next->val==val)
{
ListNode*tmp=cur->next;
cur->next=cur->next->next;
delete tmp;
}
else
{
cur=cur->next;
}
}
return head;
}
};
一个小细节:为什么while的条件是cur!=nullptr&&cur->next!=nullptr?这两个看似重复的条件实际上是不一样的。因为有一种可能是,链表中所有节点的值都为val,那么这时cur就为nullptr了。cur->next!=nullptr好理解,就是正常的终止条件(最后一个节点)
方法二:能不能归为同一种情况呢?是可以的。我们构造一个新的头节点,让这个新的头节点指向原来的头节点即可。
cpp
class Solution
{
public:
ListNode* removeElements(ListNode* head, int val)
{
ListNode*virtualhead=new ListNode(0);
virtualhead->next=head;
ListNode*cur=virtualhead;
while(cur!=nullptr&&cur->next!=nullptr)
{
if(cur->next->val==val)
{
ListNode*tmp=cur->next;
cur->next=cur->next->next;
delete tmp;
}
else
{
cur=cur->next;
}
}
head=virtualhead->next;//原来的head可能被删除了
delete virtualhead;
return head;
}
};
最后,由于要返回新链表的头节点,所以不要忘记将virtualhead->next赋给head,因为原来的head可能被删除了,会有一个新head。