您的位置:首页 > 其它

Remove Linked List Elements

2015-06-09 19:27 218 查看
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <cstring>
#include <map>
#include <cctype>
#include <cmath>
using namespace std;

struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};

class Solution {
public:
ListNode* removeElements(ListNode* head, int val) {
ListNode*cur,*nxt,*pre=head;
if(head==NULL)
return head;
for(cur=head->next;cur!=NULL;cur=nxt)
{
nxt=cur->next;
if(cur->val==val)
{
pre->next=nxt;
free(cur);
}
else
pre=cur;
}
if(head->val==val)
{
cur=head;
head=head->next;
free(cur);
}
return head;
}
};
ListNode* ListInsert(int d)
{
ListNode *tmp;
tmp=(ListNode*)malloc(sizeof(ListNode));
tmp->val=d;
tmp->next=NULL;
return tmp;
}
int main()
{
int n,val;
while(cin>>n>>val)
{
ListNode *head,*tail,*cur;
tail=(ListNode*)malloc(sizeof(ListNode));
int i,d;
for(i=0;i<n;i++)
{
cin>>d;
cur=ListInsert(d);
if(i==0)
{
head=cur;
tail=head;
}
else
{
tail->next=cur;
tail=cur;
}
}
Solution sol;
ListNode *h=sol.removeElements(head,val);
for(;h!=NULL;h=h->next)
cout<<h->val<<" ";
cout<<endl;
}
return 0;
}


View Code
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: