直接使用原来的链表来进行移除节点操作:
/**
* 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) {
// 删除头结点
while(head != nullptr && head->val == val){ // 不等于空指针 且 头结点值等于val
ListNode *temp = head;
head = head->next;
delete temp;
}
// 删除非头节点
ListNode *cur = head; // 初始化当前指针为头指针
while(cur != nullptr && cur->next != nullptr){ // 不等于空指针 且 不是尾节点
if(cur->next->val == val){ // 头结点已经进行过判断,因此判断下一个节点的val
ListNode *temp = cur->next;
cur->next = cur->next->next;
delete temp;
}
else{
cur = cur->next;
}
}
return head;
}
};
设置一个虚拟头结点在进行移除节点操作:
/**
* 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) {
// 创建并初始化dummyHead
ListNode* dummyHead = new ListNode(0);
dummyHead->next = head;
// 初始化当前指针为dummyHead
ListNode* cur = dummyHead;
while(cur->next != nullptr){
if(cur->next->val == val){
ListNode* tmp = cur->next;
cur->next = cur->next->next;
delete tmp;
}
else{
cur = cur->next;
}
}
// 还原Head,并删除dummyHead
head = dummyHead->next;
delete dummyHead;
return head;
}
};
总结:设置一个虚拟头结点,使得头结点变成了普通节点,操作上变得更简单一致