c++解法
解法1:先确定头节点,而后移动指针
/**
* 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) head = head->next;
if(head == nullptr) return nullptr;
ListNode* pre = head;
while(pre->next != nullptr){
if(pre->next->val == val) pre->next = pre->next->next;
else pre = pre->next;
}
return head;
}
};
解法2:虚拟头节点
/**
* 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) {
ListNode* dummy = new ListNode(-1);//虚拟头节点,val值随便赋
dummy ->next = head;
ListNode *pre = dummy;
while(pre->next != nullptr){
if(pre->next->val == val) pre->next = pre->next->next;
else pre = pre->next;
}
return dummy->next;
}
};