给你一个链表的头节点 head
和一个整数 val
,请你删除链表中所有满足 Node.val == val
的节点,并返回 新的头节点。
方法一:递归
class Solution {
public:
ListNode* removeElements(ListNode* head, int val) {
if(head == NULL){
return head;
}
head->next = removeElements(head->next,val);
return head->val == val ? head->next : head;
}
};
方法二:一般解法
class Solution {
public:
ListNode* removeElements(ListNode* head, int val) {
ListNode* dumyhead = new ListNode(-1, head);
ListNode* pre = dumyhead;
while (pre->next != NULL){
if(pre->next->val == val){
pre->next = pre->next->next;
}else{
pre = pre->next;
}
}
return dumyhead->next;
}
};