标签:
Remove all elements from a linked list of integers that have value val.
Example
Given: 1 --> 2 --> 6 --> 3 --> 4 --> 5 --> 6, val = 6
Return: 1 --> 2 --> 3 --> 4 --> 5
ListNode * Creat_list()
{
ListNode *p,*head,*s;
head=(ListNode*)malloc(sizeof(ListNode));
p=head;
int flag=1;
int x;
while (flag)
{
cin>>x;
if (x!=0)
{
s=(ListNode*)malloc(sizeof(ListNode));
s->val=x;
p->next=s;
p=s;
}
else
flag=0;
}
p->next=NULL;
head=head->next;
return head;
}
ListNode* removeElements(ListNode* head, int val)
{
if (head==NULL) return head;
ListNode *p,*s;
p=head;
while(p!=NULL)
{
while(val!=p->val&&p->next!=NULL)
{
s=p;
p=p->next;
}
if (val==p->val)
{
if (val==head->val)
{
head=head->next;
}
else
{
s->next=p->next;
}
}
p=p->next;
}
return head;
}
#include <iostream>
using namespace std;
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
ListNode * Creat_list();
ListNode* removeElements(ListNode* head, int val) ;
void main()
{
ListNode *head,*head1,*p;
head=Creat_list();
p=head;
while(p)
{
cout<<p->val<<" ";
p=p->next;
}
cout<<endl;
head1=removeElements(head, 6);
p=head1;
while(p)
{
cout<<p->val<<" ";
p=p->next;
}
cout<<endl;
}
ListNode * Creat_list()
{
ListNode *p,*head,*s;
head=(ListNode*)malloc(sizeof(ListNode));
p=head;
int flag=1;
int x;
while (flag)
{
cin>>x;
if (x!=0)
{
s=(ListNode*)malloc(sizeof(ListNode));
s->val=x;
p->next=s;
p=s;
}
else
flag=0;
}
p->next=NULL;
head=head->next;
return head;
}
ListNode* removeElements(ListNode* head, int val)
{
if (head==NULL) return head;
ListNode *p,*s;
p=head;
while(p!=NULL)
{
while(val!=p->val&&p->next!=NULL)
{
s=p;
p=p->next;
}
if (val==p->val)
{
if (val==head->val)
{
head=head->next;
}
else
{
s->next=p->next;
}
}
p=p->next;
}
return head;
}
标签:
原文地址:http://blog.csdn.net/sinat_24520925/article/details/45242769