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
相关文章推荐
- sql server2008 安全性管理机制
- 20150527常量变量
- 20150527常量变量_练习_运算符表达式练习
- Toast的简化用法
- [Swust OJ 715]--字典序问题(组合数预处理/数位dp)
- 在线判题 (模拟)http://202.196.1.132/problem.php?id=1164
- HDU - 4734 F(x) (2013成都网络游戏,数字DP)
- 异常
- 20150527运算符表达式
- 集锦续集
- 关于Android Studio无法更新安装而导致无法启动的问题
- 【leetcode】【单链表】【109】Convert Sorted List to Binary Search Tree
- 【leetcode】【单链表】【109】Convert Sorted List to Binary Search Tree
- Linux下编译安装Apache及模块
- Xcode 6.1 做ipa企业级分发(In-House模式)详细步骤
- maven安装到本地库时如何加入工程本地jar包
- Hdu 5262 最强密码(dp)
- adb logcat打印log丢失
- C# 简单工厂模式
- 20150526数据编码_练习