给你一个链表的头节点 head
和一个整数 val
,请你删除链表中所有满足 Node.val == val
的节点,并返回 新的头节点 。
链表定义:
//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) {
// 如果head的val等于val,删除head
while (head != NULL && head->val == val) {
ListNode* temp = head;
head = head->next;
delete temp;
}
// 删除非头节点
ListNode* cur = head; // 定义移动指针先指向head
while (cur != NULL && cur->next != NULL) { // cur不是空的,且不是最后一个元素
if (cur->next->val == val) {
ListNode* temp = cur->next;
cur->next = cur->next->next;
delete temp;
}
else {
cur = cur->next;
}
}
return head;
}
};
解法二:
// 设置一个虚拟头节点,让其指向head
class Solution {
public:
ListNode* removeElements(ListNode* head, int val) {
ListNode* virtualHead = new ListNode(0); // 虚拟头节点
virtualHead->next = head;
ListNode* cur = virtualHead;
while (cur->next != NULL) {
if (cur->next->val == val) {
ListNode* temp = cur->next;
cur->next = cur->next->next;
delete temp;
}
else {
cur = cur->next;
}
}
head = virtualHead->next;
delete virtualHead; // 最后要释放掉虚拟头节点
return head;
}
};