mycode  88.29%

关键是一定要head前新建一个节点,否则要分类讨论很多次来避免slow或者fast出现None.next的错误

# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None class Solution(object):
def removeNthFromEnd(self, head, n):
"""
:type head: ListNode
:type n: int
:rtype: ListNode
"""
dummy = ListNode(-1)
dummy.next = head
slow = fast = dummy
#print(n,head.val)
while n:
fast = fast.next
n -= 1
#print(n,head.val,fast)
while fast and fast.next:
fast = fast.next
slow = slow.next
slow.next = slow.next.next
return dummy.next

例如,下面这种情况就要分情况讨论,但是会更快

# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None class Solution:
def removeNthFromEnd(self, head, n):
fast = slow = head
for _ in range(n):
fast = fast.next
if not fast: #例如1-》2-》3-》4-》None,n=4或者5的时候,删除的就应该是第一个节点,所以返回head.next就好
return head.next
while fast.next:
fast = fast.next
slow = slow.next
slow.next = slow.next.next
return head

最新文章

  1. 【Effective Java】12、避免过度同步
  2. 匹配img和a
  3. 关于Yii2中count方法的使用
  4. JavaScrip拖动动画中的常见BUG
  5. 【树形DP/搜索】BZOJ 1827: [Usaco2010 Mar]gather 奶牛大集会
  6. Spring 使用注解方式进行事务管理
  7. Hibernate之Session缓存以及操作Session缓存的相关方法
  8. zoj2112
  9. 小强的HTML5移动开发之路(50)——jquerymobile页面初始化过程
  10. 习题10-1 UVA 11040(无聊水一水)
  11. 中位数——二维坐标下的中位数lightoj1349
  12. 项目ITP(五) spring4.0 整合 Quartz 实现任务调度
  13. 如何写好一篇高质量的IEEE/ACM Transaction级别的计算机科学论文?
  14. mysql连接数设置操作(Too many connections)及设置md5值的加密密码
  15. wps word改多级编号为2.1
  16. Grafana 监控系统是否重启
  17. hadoop2.6.4集群的搭建
  18. Debug 路漫漫-04
  19. taskset
  20. xgboost与sklearn的接口

热门文章

  1. 【Lucene】小谈lucene的BooleanQuery查询对象
  2. javascript中的数据渲染与提取
  3. 在mysql 上如何在不影响生产的情况下删除一个大表
  4. 从FBV到CBV三(权限)
  5. 新增分区格式化时提示设备文件不存在:--- No such file or directory的处理方法
  6. The Multilinear Structure of ReLU Networks
  7. zabbix的简单操作(监控客户端MySQL数据包库)
  8. 使用rpm安装mysql5.6(简单安装 实验使用)
  9. 模拟客户端向服务器发起请求(从Fiddler抓包到Jmeter接口测试)
  10. Gym - 101987G Secret Code (概率+数学积分)