leetcode-easy-listnode-19 remove nth node from end of list
2024-10-21 18:56:01
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
最新文章
- 【Effective Java】12、避免过度同步
- 匹配img和a
- 关于Yii2中count方法的使用
- JavaScrip拖动动画中的常见BUG
- 【树形DP/搜索】BZOJ 1827: [Usaco2010 Mar]gather 奶牛大集会
- Spring 使用注解方式进行事务管理
- Hibernate之Session缓存以及操作Session缓存的相关方法
- zoj2112
- 小强的HTML5移动开发之路(50)——jquerymobile页面初始化过程
- 习题10-1 UVA 11040(无聊水一水)
- 中位数——二维坐标下的中位数lightoj1349
- 项目ITP(五) spring4.0 整合 Quartz 实现任务调度
- 如何写好一篇高质量的IEEE/ACM Transaction级别的计算机科学论文?
- mysql连接数设置操作(Too many connections)及设置md5值的加密密码
- wps word改多级编号为2.1
- Grafana 监控系统是否重启
- hadoop2.6.4集群的搭建
- Debug 路漫漫-04
- taskset
- xgboost与sklearn的接口
热门文章
- 【Lucene】小谈lucene的BooleanQuery查询对象
- javascript中的数据渲染与提取
- 在mysql 上如何在不影响生产的情况下删除一个大表
- 从FBV到CBV三(权限)
- 新增分区格式化时提示设备文件不存在:--- No such file or directory的处理方法
- The Multilinear Structure of ReLU Networks
- zabbix的简单操作(监控客户端MySQL数据包库)
- 使用rpm安装mysql5.6(简单安装 实验使用)
- 模拟客户端向服务器发起请求(从Fiddler抓包到Jmeter接口测试)
- Gym - 101987G Secret Code (概率+数学积分)