方法一:指针遍历
class Solution {
public:
ListNode* deleteNode(ListNode* head, int val) {
ListNode* dummy=new ListNode(-1);
dummy->next=head;
ListNode* cur=dummy;
while(cur->next) {
if(cur->next->val==val) {
cur->next=cur->next->next;
}
else cur=cur->next;
}
return dummy->next;
}
};
方法二:递归
class Solution {
public:
ListNode* deleteNode(ListNode* head, int val) {
if(!head) return head;
if(head->val==val) return head->next;
head->next=deleteNode(head->next,val);
return head;
}
};