19. Remove Nth Node From End of List
2024-10-12 19:31:12
题目:
Given a linked list, remove the nth node from the end of list and return its head.
For example,
Given linked list: 1->2->3->4->5, and n = 2. After removing the second node from the end, the linked list becomes 1->2->3->5.
Note:
Given n will always be valid.
Try to do this in one pass.
代码:
从链表中删除从右向左数第N个元素,况且只能遍历链表一遍。
所以,需要定义两个指针,相差是N个元素,同时向前遍历,当靠前的元素走到最后的时候,在后面的元素刚好与最后一个元素距离为N,删除即可。
于是:
#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
"""
p = head
q = head
if head.next ==None:return []
for i in range(0,n):
q = q.next
if not q : return head.next
while q.next:
p = p.next
q = q.next
temp = p.next.next
p.next = temp
return head if __name__=='__main__':
arr = [1,2]
p = ListNode(arr[0])
head = p
for i in arr[1:]:
p.next = ListNode(i)
p = p.next
s=Solution()
q=s.removeNthFromEnd(head,2)
while q:
print (q.val)
q = q.next
最新文章
- nginx $document_uri 防止死循环
- mysql5.7.10 的源码安装
- ecshop商品子分类点击下拉,子分类空时,直接跳转功能
- 高德携手阿里云发布“LBS云”,账户打通只是第一步
- hdu 1203 概率+01背包
- 二 、打开地图《苹果iOS实例编程入门教程》
- [SoapUI] SoapUI JDBC REST 连接 Netezza
- 黄页js-sdk开发总结分享
- iOS第三方类库JSPatch(热更新)
- Java的加密与解密
- 从SVN导出指定版本号之间修改的文件
- 安卓 Dialogs(对话框)
- 设计模式 - 命令模式(command pattern) 具体解释
- 观察者模式模拟YUI事件机制
- c#生成word文档
- angularLoad(用以异步加载js文件)
- Spring MVC的DispatcherServlet
- [EXTJS5学习笔记]第二十六节 在eclipse/myeclipse中使用sencha extjs的插件
- 《Exception团队》第二次作业:团队项目选题报告
- php 关于经纬度距离计算方法