/** * struct ListNode { * int val; * struct ListNode *next; * ListNode(int x) : val(x), next(nullptr) {} * }; */ // 题目给定的链表节点结构(无需重复定义,此处为示例完整性展示) class Solution { public: ListNode* removeElements(ListNode* head, int val) { // 创建虚拟头节点,统一处理头节点删除的情况 ListNode* dummy = new ListNode(0); dummy->next = head; ListNode* cur = dummy; // 遍历指针从虚拟头节点开始 while (cur->next != nullptr) { // 遍历至链表末尾 if (cur->next->val == val) { ListNode* temp = cur->next; // 暂存待删除节点 cur->next = cur->next->next; // 跳过待删除节点 delete temp; // 释放待删除节点的内存 } else { cur = cur->next; // 指针后移 } } ListNode* newHead = dummy->next; // 保存新链表的头节点 delete dummy; // 释放虚拟头节点的内存 return newHead; } };