日野弥生:勉強しよう
LeetCode 203 - 移除链表元素
发表于2025年01月19日
先处理掉从头指针开始所有与指定值相等的点,只到第一个不相等的点再开始进行while循环判断当前节点是否和指定值相等,进行链表结点删除和前后链接。
class Solution {
public:
ListNode* removeElements(ListNode* head, int val) {
while(head && head->val == val)
{
head = head->next;
}
ListNode* curr = head, *prev = nullptr;
while(curr)
{
if(curr->val == val)
{
ListNode *next = curr->next;
prev->next = next;
delete curr;
curr = next;
}
else
{
prev = curr;
curr = curr->next;
}
}
return head;
}
};