203. Remove Linked List Elements
2017-01-12 08:03
465 查看
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.
这道题创建一个新的node指向head,留作返回用。再创建一个currNode进行node操作用。首先确保currNode和currNode.next不为null,再判断currNode.next的val是不是等于target,是的话让currNode.next等于currNode.next.next,删除之前的currNode.next,不想等的话让currNode等于currNode.next,进行下面的判断。代码如下:
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
public class Solution {
public ListNode removeElements(ListNode head, int val) {
if (head == null) {
return head;
}
ListNode preHead = new ListNode(0);
preHead.next = head;
ListNode currNode = preHead;
while (currNode != null && currNode.next != null) {
if (currNode.next.val == val) {
currNode.next = currNode.next.next;
} else {
currNode = currNode.next;
}
}
return preHead.next;
}
}
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.
这道题创建一个新的node指向head,留作返回用。再创建一个currNode进行node操作用。首先确保currNode和currNode.next不为null,再判断currNode.next的val是不是等于target,是的话让currNode.next等于currNode.next.next,删除之前的currNode.next,不想等的话让currNode等于currNode.next,进行下面的判断。代码如下:
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
public class Solution {
public ListNode removeElements(ListNode head, int val) {
if (head == null) {
return head;
}
ListNode preHead = new ListNode(0);
preHead.next = head;
ListNode currNode = preHead;
while (currNode != null && currNode.next != null) {
if (currNode.next.val == val) {
currNode.next = currNode.next.next;
} else {
currNode = currNode.next;
}
}
return preHead.next;
}
}
相关文章推荐
- 基础10
- 反骨仔的 2016 年度全文目录索引
- 手把手教你搭建属于自己的博客
- 最小生成树(普利姆算法、克鲁斯卡尔算法)
- BZOJ 1061: [Noi2008]志愿者招募
- spring boot——结合docker
- libevent源码分析:evmap_io_active_函数
- igllib 203 Curvature directions
- 【菜鸟数据库学习日记】从头开始学MySQL(2)
- es6笔记1^_^let、string、number、math
- NET Core写了一个轻量级的Interception框架[开源]
- Android项目实践之菜鸟养成(五)用户体验之Android活动的生命周期
- JAVA知乎爬虫
- Zookeeper配置文件中的配置项解释和Zookeeper的安装
- Core中使用Razor视图引擎渲染视图为字符串 阅读目录
- zoj2500
- TensorFlow官方教程学习笔记(四)——MNIST数据集的读取
- C#使用ES
- net core 认证及简单集群
- 软件工程需求分析