一道基础的链表相关题目,在删除时对头节点进行单独处理。
cpp
/**
* 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 != NULL && head->val == val){
ListNode * t = head;
head = head->next;
delete t;
}
ListNode * cur = head;
while(cur != NULL && cur->next != NULL){
if(cur->next->val == val){
ListNode * t = cur->next;
cur->next = cur->next->next;
delete t;
}else{
cur = cur->next;
}
}
return head;
}
};
另外一种写法是设置一个虚拟节点指向头节点,这样就无需对头节点进行单独处理,最后将head指向虚拟节点的下一个节点。
cpp
class Solution {
public:
ListNode* removeElements(ListNode* head, int val) {
ListNode* dummyHead = new ListNode(0); // 设置一个虚拟头结点
dummyHead->next = head; // 将虚拟头结点指向head,这样方便后面做删除操作
ListNode* cur = dummyHead;
while (cur->next != NULL) {
if(cur->next->val == val) {
ListNode* tmp = cur->next;
cur->next = cur->next->next;
delete tmp;
} else {
cur = cur->next;
}
}
head = dummyHead->next;
delete dummyHead;
return head;
}
};