考点
- 虚拟头结点
- 手动清理结点内存
思路
代码
class Solution {
public:
ListNode* removeElements(ListNode* head, int val)
{
ListNode *dummyHead = new ListNode();
dummyHead->next = head;
ListNode *cur = dummyHead;
while(cur->next != nullptr)
{
if(cur->next->val == val)
{
ListNode *tmp = cur->next;
cur->next = cur->next->next;
delete tmp;
}
else
cur = cur->next;
}
head = dummyHead->next;
delete dummyHead;
return head;
}
};