203_Removed-Linked-List-Elements

Description

Remove all elements from a linked list of integers that have value val.

Example:

Input:  1->2->6->3->4->5->6, val = 6
Output: 1->2->3->4->5

Solution

Java solution 1

/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode removeElements(ListNode head, int val) {
while (head != null && head.val == val) {
head = head.next;
} if (head == null) {
return null;
} ListNode prev = head;
while (prev.next != null) {
if (prev.next.val == val) {
prev.next = prev.next.next;
} else {
prev = prev.next;
}
} return head;
}
}

Runtime: 7 ms.

Java solution 2

Using dummy head node.

/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode removeElements(ListNode head, int val) {
ListNode dummyHead = new ListNode(-1);
dummyHead.next = head; ListNode prev = dummyHead;
while (prev.next != null) {
if (prev.next.val == val) {
prev.next = prev.next.next;
} else {
prev = prev.next;
}
} return dummyHead.next;
}
}

Runtime: 8 ms.

Python solution

# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None class Solution:
def removeElements(self, head, val):
"""
:type head: ListNode
:type val: int
:rtype: ListNode
"""
dummy_head = ListNode(-1)
dummy_head.next = head prev = dummy_head
while prev.next is not None:
if prev.next.val == val:
prev.next = prev.next.next
else:
prev = prev.next return dummy_head.next

Runtime: 88 ms. Your runtime beats 74.70 % of python3 submissions.

最新文章

  1. Sentinel-Redis高可用方案(一):主从复制
  2. Ubuntu下MySQL忘记root密码重置
  3. 用dubbo+zookeeper+spring搭建一个简单的http接口程序
  4. Java 获取今天之前的七天 的日期
  5. python高级编程之描述符与属性03
  6. 理解Java多态
  7. putty完全使用手册--多窗口---git提交---连接数据库--自动日志显示
  8. BigDecimal类型转换
  9. gp工具的许可
  10. 解决win10中chm内容显示为空白的问题
  11. Innodb ,MyISAM
  12. MySQL的四种不同查询的分析
  13. Golang cron 定时任务使用
  14. [css]浮动造成的影响
  15. js事件队列
  16. MyEclipse部署项目时点finish点不动finish按钮灰色的
  17. 为什么MyISAM会比Innodb的查询速度快
  18. Ubuntu 16.09下iptables通过raw表实现日志输出和调试
  19. TensorFlowIO操作(二)----读取数据
  20. 在Chem 3D软件用什么方法可以改变背景

热门文章

  1. XML--使用XML来将字符串分隔成行数据
  2. XML--将XML中数据提取出转换成表2
  3. 比较git commit 两个版本之间次数
  4. 对Integer类中的私有IntegerCache缓存类的一点记录
  5. C# 依赖注入 & MEF
  6. how to remote debug in vs 2013
  7. WPF 背景网格图
  8. linux进程管理(二)
  9. Java Web 学习与总结(二)Servlet核心接口+Servlet3.0配置
  10. URL的三类编码格式(JavaScript实现)