思路1
处理头节点,然后遍历下一个节点,只有确保下一个节点不是要移除的节点时再跳到下一个节点
代码1
class Solution {
public:
ListNode* removeElements(ListNode* head, int val) {
while(head != nullptr && head->val == val){
head = head->next;
}
ListNode* front = head;
while(front != nullptr &&front->next != nullptr){
if(front->next!=nullptr && front->next->val == val){
front->next = front->next->next;
}else
front = front->next;
}
return head;
}
};
思路2
设置空白头节点,这样不用单独处理头节点
代码2
class Solution {
public:
ListNode* removeElements(ListNode* head, int val) {
ListNode* bankNode = new ListNode();
bankNode->next = head;
ListNode* cur = bankNode;
while(cur->next != nullptr){
if(cur->next->val == val){
cur->next = cur->next->next;
}else
cur = cur->next;
}
return bankNode->next;
}
};