https://leetcode.cn/problems/remove-linked-list-elements/description/

<aside> 💡

重点:定义一个虚拟头节点,将其指向原先的头节点。

注意:C++中记得在最后回收被删除的节点与虚拟头节点

</aside>

// 使用虚拟头节点使头节点与非头节点的操作方式统一(相当于将头节点也变为非头节点)
ListNode* removeElements(ListNode* head, int val) {
	ListNode* dummyHead = new ListNode(0);
	dummyHead->next = head;
	
	// 遍历的是->next,所以cur指向dummyHead
	ListNode* cur = dummyHead;
	while (cur->next) {
		// 如果下一节点的值需要删除,就跳过该节点,将next与下下个节点相连
		// 如果下一节点不需要删除直接移到下一节点即可
		if (cur->next->val == val) {
			ListNode* temp = cur->next;
			cur->next = cur->next->next;
			delete temp;
		} else {
			cur = cur->next;
		}
	}
	head = dummyHead->next;
	delete dummyHead;
	return head;
}