整体代码逻辑如下:
- 如果链表为空,返回nullptr;
- 如果开头的元素都等于val,那么就让头节点向后移;
- 当遇到第一个不为val的结点时,作为新链表的头节点,并遍历链表,遇到等于val的结点就跳过;
c++代码如下:
class Solution {
public:
ListNode* removeElements(ListNode* head, int val) {
if(head==nullptr){
return nullptr;
}
while(head!=nullptr && head->val==val){
head=head->next;
}
ListNode* cur=head;
while(cur!=nullptr && cur->next!=nullptr){
if(cur->next->val==val){
cur->next=cur->next->next;
}
else{
cur=cur->next;
}
}
return head;
}
};