题目

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.

代码:oj在线测试通过 Runtime: 188 ms

 # Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None class Solution:
# @return a ListNode
def removeNthFromEnd(self, head, n):
if head is None:
return head dummyhead = ListNode(0)
dummyhead.next = head
p1 = dummyhead
p2 = dummyhead for i in range(0,n):
p1 = p1.next while p1.next is not None:
p1 = p1.next
p2 = p2.next
if p1.next is None:
break p2.next = p2.next.next return dummyhead.next

思路

Linked List基本都需要一个虚表头,这道题主要思路是双指针

让第一个指针p1先走n步,然后再让p1和p2一起走;当p1走到链表最后一个元素的时候,p2就走到了倒数n+1个元素的位置;这时p2.next向表尾方向跳一个。

注意下判断条件是p1.next is not None,因此在while循环中添加判断p1.next是否为None的保护判断。

再有就是注意一下special case的情况,小白我的习惯是在最开始就把这种case都判断出来;可能牺牲了代码的简洁性,有大神路过也请拍砖指点。

最新文章

  1. shell 中的与、或表达式
  2. struts2 CVE-2012-0392 S2-008 Strict DMI does not work correctly allows remote command execution and arbitrary file overwrite
  3. java 在接口里函数不能重载?
  4. 在strut.xml 中使用ognl
  5. C#删除文件和文件夹到回收站
  6. CentOS6.0/RedHat Server 6.4安装配置过程 详细图解!
  7. [数据库连接字符串] Access 连接字符串
  8. 微软开放技术开发了适用于 Windows Azure 移动服务的开源 Android SDK
  9. nvarchar and nchar
  10. Linux vim编辑器
  11. [LeetCode] Dota2 Senate 刀塔二参议院
  12. python之模块之shutil模块
  13. Tag
  14. java微信小程序调用支付接口(转)
  15. jquery 获取访问当前页面的开源设备信息
  16. python3之模块psutil系统性能信息
  17. oracle中验证身份证是否合法的函数脚本
  18. P03-Python装饰器
  19. 怎样在 Azure 应用服务中生成和部署 Java API 应用
  20. ARIA(Accessible Rich Internet Application)

热门文章

  1. webpack踩坑
  2. AFNetworking 初探
  3. 快算24点,POJ(3983)
  4. spring教程(一):简单实现(转)
  5. 矩阵——特征向量(Eigenvector)
  6. 通过eclipse启动tomcat设置JAVA_OPTS失败的解决方案
  7. linux服务器安装nginx及使用
  8. JavaScript 十行原生代码实现复制内容到剪贴板
  9. ionic 命令cordova
  10. Ansible工作架构和原理