链表:
carl整理链表知识点:# 关于链表,你该了解这些!
carl整理:移除链表元素
203.移除链表元素
/**
* 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){
head = head ->next;
}
ListNode* cur = head;
while((cur != NULL )&& (cur->next != NULL)){
if(cur ->next ->val == val){
cur -> next = cur -> next -> next;
}
else{
cur = cur -> next;
}
}
return head;
}
};