捕获.PNG
#include <iostream>
#include <vector>
#include <list>
#include <stack>
#include <queue>
using namespace std;
/* 链表定义 */
struct ListNode
{
int val;
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)
{
if (cur->next->val == val)
{
ListNode *tmp = cur->next;
cur->next = cur->next->next;
delete tmp; // 删除已经移除的节点,清理节点内存
}
else
{
cur = cur->next;
}
}
head = dummy->next; // 返回移除链表元素后,新链表的头节点
delete dummy;
return head;
}
};
网友评论