leetcode 203 Remove-Linked-List-Elements
2016-06-20 21:45
375 查看
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
Credits:
Special thanks to @mithmatt for adding this problem and creating all test cases.
Subscribe to see which companies asked this question
class Solution {
public:
ListNode *removeElements(ListNode *head, int val) {
if(head == NULL) return head;
ListNode *pre=NULL, *cur=head, *temp=NULL;
for(cur=head; cur!=NULL;) {
temp = cur->next;
if(cur->val == val) {
if(pre==NULL) {
head = head->next;
cur = head;
} else{
pre->next = cur->next;
}
} else {
pre = cur;
}
cur = temp;
}
return head;
}
}
Example
Given: 1 --> 2 --> 6 --> 3 --> 4 --> 5 --> 6, val = 6
Return: 1 --> 2 --> 3 --> 4 --> 5
Credits:
Special thanks to @mithmatt for adding this problem and creating all test cases.
Subscribe to see which companies asked this question
class Solution {
public:
ListNode *removeElements(ListNode *head, int val) {
if(head == NULL) return head;
ListNode *pre=NULL, *cur=head, *temp=NULL;
for(cur=head; cur!=NULL;) {
temp = cur->next;
if(cur->val == val) {
if(pre==NULL) {
head = head->next;
cur = head;
} else{
pre->next = cur->next;
}
} else {
pre = cur;
}
cur = temp;
}
return head;
}
}
相关文章推荐
- 计算阶乘的另一些有趣的算法(转载)
- QReadWriteLock上锁容忍的等待时间是多久?
- HDFS深入浅析
- FTP服务器常规操作
- ArchLinux下十八岁的感悟
- Android 平滑图片加载和缓存库 Glide
- 堆(heap)和栈(stack)有什么区别
- 源码剖析目录
- 《Java小游戏实现》:坦克大战(续一)
- 软件工程个人总结
- oracle第一天
- JAVA中native方法调用C语言实现学习
- 快学Scala第8章----继承
- android 应用按返回键仍然在后台运行
- 【codevs 1078】最小生成树
- mybatis_user_guide(8) 日志
- 用Linq 解决 数据的多字段分组统计(VB.net)
- 操作系统:进程管理
- memcpy与memmove的区别
- 微信开发的本地调试环境搭建