1 classSolution {2 Public:3listnode* removeelements (listnode* head,intval) {4Listnode*cur,*nxt,*pre=head;5 if(head==NULL)6 returnhead;7 for(cur=head->next;cur!=null;cur=NXT)8 {9Nxt=cur->Next;Ten if(cur->val==val) One { Apre->next=NXT; - Free (cur); - } the Else -Pre=cur; - } - if(head->val==val) + { -Cur=head; +Head=head->Next; A Free (cur); at } - returnhead; - } -};
View Code
Do the chain list problem if the condition allows, it is best to manually simulate again, in doing this problem because forgot to write a sentence pre=cur, has been wrong.
Full code:
1#include <iostream>2#include <string>3#include <vector>4#include <algorithm>5#include <cstring>6#include <map>7#include <cctype>8#include <cmath>9 using namespacestd;Ten One structListNode { A intVal; -ListNode *Next; -ListNode (intx): Val (x), Next (NULL) {} the }; - - classSolution { - Public: +listnode* removeelements (listnode* head,intval) { -Listnode*cur,*nxt,*pre=head; + if(head==NULL) A returnhead; at for(cur=head->next;cur!=null;cur=NXT) - { -Nxt=cur->Next; - if(cur->val==val) - { -pre->next=NXT; in Free (cur); - } to Else +Pre=cur; - } the if(head->val==val) * { $Cur=head;Panax NotoginsengHead=head->Next; - Free (cur); the } + returnhead; A } the }; +listnode* Listinsert (intd) - { $ListNode *tmp; $tmp= (listnode*) malloc (sizeof(ListNode)); -Tmp->val=D; -tmp->next=NULL; the returntmp; - }Wuyi intMain () the { - intN,val; Wu while(cin>>n>>val) - { AboutListNode *head,*tail,*cur; $Tail= (listnode*) malloc (sizeof(ListNode)); - inti,d; - for(i=0; i<n;i++) - { ACin>>D; +Cur=Listinsert (d); the if(i==0) - { $Head=cur; theTail=head; the } the Else the { -tail->next=cur; inTail=cur; the } the } About solution Sol; theListNode *h=sol.removeelements (head,val); the for(;h!=null;h=h->next) thecout<" "; +cout<<Endl; - } the return 0;Bayi}
View Code
Remove Linked List Elements