![](https://img-blog.csdnimg.cn/img_convert/b0f87be4f14d47448a86ac96a005e876.png)
![](https://img-blog.csdnimg.cn/img_convert/05bd9e8a929942409644e7dc18c16563.png)
思路
遍历链表节点,找出val并删除。
方法一 直接处理
直接在原链表上修改,这时候我们需要考虑头结点是否与val相等。
class Solution {
public:
ListNode* removeElements(ListNode* head, int val) {
//1.处理头结点值为val的情况
while (head != nullptr && head->val == val)
{
ListNode* tmp = head;
head = head->next;
delete tmp;
}
//2.若头结点为空,直接返回就好
if (head == nullptr)
return nullptr;
//3.下面只剩下头结点不为空且头结点值不等于val的情况了
ListNode* prev = head;
ListNode* cur = head->next;
while (cur != nullptr)
{
if (cur->val == val)
{
ListNode* tmp = cur;
prev->next = cur->next;
cur = cur->next;
delete tmp;
}
else
{
prev = cur;
cur = cur->next;
}
}
return head;
}
};
方法二 虚拟头结点
即在原本头结点前加一个哨兵位,这样我们就不需要再单独考虑原头结点的情况了,推荐用此方法。
class Solution {
public:
ListNode* removeElements(ListNode* head, int val) {
if (head == nullptr)
return nullptr;
ListNode* dummy = new ListNode(0);
dummy->next = head;
//下面处理的是原头结点不为空的情况,相当于方法一的3
ListNode* prev = dummy;
ListNode* cur = head;
while (cur != nullptr)
{
if (cur->val == val)
{
ListNode* tmp = cur;
cur = cur->next;
prev->next = cur;
delete tmp;
}
else
{
prev = cur;
cur = cur->next;
}
}
return dummy->next;
}
};