题目:

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

最新文章

  1. nginx $document_uri 防止死循环
  2. mysql5.7.10 的源码安装
  3. ecshop商品子分类点击下拉,子分类空时,直接跳转功能
  4. 高德携手阿里云发布“LBS云”,账户打通只是第一步
  5. hdu 1203 概率+01背包
  6. 二 、打开地图《苹果iOS实例编程入门教程》
  7. [SoapUI] SoapUI JDBC REST 连接 Netezza
  8. 黄页js-sdk开发总结分享
  9. iOS第三方类库JSPatch(热更新)
  10. Java的加密与解密
  11. 从SVN导出指定版本号之间修改的文件
  12. 安卓 Dialogs(对话框)
  13. 设计模式 - 命令模式(command pattern) 具体解释
  14. 观察者模式模拟YUI事件机制
  15. c#生成word文档
  16. angularLoad(用以异步加载js文件)
  17. Spring MVC的DispatcherServlet
  18. [EXTJS5学习笔记]第二十六节 在eclipse/myeclipse中使用sencha extjs的插件
  19. 《Exception团队》第二次作业:团队项目选题报告
  20. php 关于经纬度距离计算方法

热门文章

  1. IT职场人的“存在主义”
  2. 学python
  3. Ubuntu/mint清理系统垃圾
  4. python基础回顾1
  5. Leetcode 39. Combination Sum
  6. 常见linux命令释义(第九天)—— Bash Shell 的操作环境Shell 中的管道命令一些管道命令
  7. HTML-如何让自己的网页标题处可以显示网站的logo?
  8. Google 地图 API V3 之控件
  9. thinkphp语言包
  10. 最大公共字串LCS问题(阿里巴巴)