这是我的方法,感觉比较笨,就是用保存前驱的方法,来连接节点。
ListNode* removeElements(ListNode* head, int val) {
ListNode *pre_node=head,*next_node=NULL,*old_pre_node=head;
while(pre_node){
next_node=pre_node->next;
if(pre_node->val==val&&pre_node==head){ //head
ListNode *t=head;
head=next_node;
delete t;
}
else if(pre_node->val==val&&pre_node!=head){
old_pre_node->next=next_node;
delete pre_node;
pre_node=NULL;
}
if(pre_node!=NULL){ //if pre_node been deleted,then keep the old_pre_node unchanged
old_pre_node=pre_node;
pre_node=next_node;
}
return head;
}
多的不说,来看看leetcode上大神的解法:( 出处)
ListNode* removeElements(ListNode* head, int val) {
ListNode ** phead = &head;
while (1) {
while (*phead && (*phead)->val == val)
*phead = (*phead)->next;
if (*phead) phead = &(*phead)->next;
else break;
}
return head;
}
递归解法:(出处)
ListNode* removeElements(ListNode* head, int val) {
if (!head) return 0;
ListNode * tail = removeElements(head->next, val);
if (head->val == val) return tail; else {
head->next = tail;
return head;
}
}