- 思路
注意当移除的节点是头结点时,需要使用虚拟节点
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution
{
public:
ListNode* removeElements(ListNode* head, int val)
{
ListNode *dummyNode = new ListNode(0);//构建虚拟节点
dummyNode->next = head;//虚拟节点指向头结点
ListNode *cur = dummyNode;
while (cur->next != nullptr)
{
if (cur->next->val == val)
{
//ListNode *temp = cur->next;
cur->next = cur->next->next;
//delete temp;
}
else
{
cur = cur->next;
}
}
return dummyNode->next;
}
};