[codesyntax lang=”php”]
#include<iostream>
#include<stdlib.h>
#include<cstring>
using namespace std;
struct ListNode{
int val;
ListNode *next;
ListNode(int x): val(x),next(NULL){}
};
void remove(ListNode **head, int target){
ListNode* newhead=*head;
while(newhead->val==target) newhead=newhead->next;
if(newhead==NULL) *head=NULL;
ListNode* p=newhead;
ListNode* q=newhead->next;
while(q!=NULL){
if(q->val==target){
q=q->next;
p->next=q;
}
else{
p=q;
q=q->next;
}
}
*head=newhead;
}
void print(ListNode* head){
while(head){
cout<<head->val<<endl;
head=head->next;
}
}
int main(){
ListNode* p1=new ListNode(1);
ListNode* p2=new ListNode(1);
ListNode* p3=new ListNode(3);
ListNode* p4=new ListNode(4);
ListNode* p5=new ListNode(5);
ListNode* p6=new ListNode(1);
ListNode* p7=new ListNode(1);
p1->next=p2;
p2->next=p3;
p3->next=p4;
p4->next=p5;
p5->next=p6;
p6->next=p7;
remove(&p1,1);
print(p1);
}
[/codesyntax]

Leave a Reply