题目地址: https://leetcode-cn.com/problems/remove-linked-list-elements/
题目描述: 删除链表中等于给定值 val 的所有节点
参考代码:
class Solution {
public:
ListNode* removeElements(ListNode* head, int val) {
while (head && head->val == val) {
ListNode *temp = head;
head = head ->next;
delete temp;
}
ListNode *current = head;
while (current && current->next) {
if (current->next->val == val) { // 是 next
ListNode *temp = current->next;
current->next = current->next->next;
delete temp;
} else {
current = current->next;
}
}
return head;
}
};
注意点: 删除元素,记得释放!