LeetCode -- 删除链表中值为k的元素
2015-07-23 09:17
267 查看
本题目比较直接,一次遍历遇到匹配的元素直接删除(通过n.next = n.next.next)就可以了,只是需要考虑到:
1.首节点的情况
2.末节点的情况
以下为实现:
public ListNode RemoveElements(ListNode head, int val) {
// null list
if(head == null){
return null;
}
// constains only one node
if(head.next == null && head.val == val){
return null;
}
//remove first nodes
while(head.val == val){
if(head.next == null){
break;
}
head = head.next;
}
var tmp = head;
// nodes in between
while(head.next != null){
if(head.next.val == val){
head.next = head.next.next;
}
else{
head = head.next;
}
if(head.next == null){
break;
}
}
// last node
if(head.val == val){
return null;
}
// restore head node
head = tmp;
return head;
}
1.首节点的情况
2.末节点的情况
以下为实现:
public ListNode RemoveElements(ListNode head, int val) {
// null list
if(head == null){
return null;
}
// constains only one node
if(head.next == null && head.val == val){
return null;
}
//remove first nodes
while(head.val == val){
if(head.next == null){
break;
}
head = head.next;
}
var tmp = head;
// nodes in between
while(head.next != null){
if(head.next.val == val){
head.next = head.next.next;
}
else{
head = head.next;
}
if(head.next == null){
break;
}
}
// last node
if(head.val == val){
return null;
}
// restore head node
head = tmp;
return head;
}
相关文章推荐
- IOS开发UI篇--IOS动画(Core Animation)总结
- 本地配置yum源的方法
- python的迭代器与生成器实例详解
- iOS开发学习笔记二 —— Charles
- Unix & Linux 命令分类表
- C++学习笔记之虚拟与多态
- hdu 3038 How Many Answers Are Wrong
- Adaboost 算法的原理与推导
- 使用内存映射文件读写大文件
- hive UDF 分享 通过IP地址获取IDC//省份/城市的信息http://my.oschina.net/wangjiankui/blog/263994
- java数据库 DBHelper
- 多重费用的完全背包 HDU2159
- [转载] 虚拟机是怎么实现的
- 查看win10的激活信息和版本号
- Android基础入门教程——2.3.3 Button(按钮)与ImageButton(图像按钮)
- 泛型算法sort,fill,fill—n,stable—sort,accumulate
- ORACLE 定时执行存储过程<一>
- ORACLE 12C新特性——CDB与PDB
- 源码推荐(7.23):FMDBModel使你的实体类具备直接操作数据库的功能,Switch 开关动画效果
- Gson中fromJson方法的返回值