给你一个链表的头节点 head 和一个整数 val ,请你删除链表中所有满足 Node.val == val 的节点,并返回 新的头节点 。
示例 1:
输入:head = [1,2,6,3,4,5,6], val = 6
输出:[1,2,3,4,5]
/**
* 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 *tmp=head;
head=head->next;
delete tmp;
}
ListNode *inside=head;
while(inside!=NULL&&inside->next!=NULL){
if(inside->next->val==val){
ListNode *tmp=inside->next;
inside->next=inside->next->next;
delete tmp;
}
else{
inside=inside->next;
}
}
return head;
}
};
来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/remove-linked-list-elements