https://leetcode.cn/problems/remove-linked-list-elements/
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution
{
public:
ListNode* removeElements(ListNode* head, int val)
{
if(head == nullptr)
{
return 0;
}
ListNode *head2 = new ListNode(0); // 创建新链表存储结果链表
// 原因:为便于对head链表的头结点进行判断
head2->next = head;
ListNode *p = head2;
while(p->next != nullptr)
{
if(p->next->val == val)
{
p->next = p->next->next;
}
else
{
p = p->next;
}
}
return head2->next;
}
};