leetcode之-题19
2016-02-18 14:20
302 查看
题目
19. Remove Nth Node From End of List
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-1,每次两个指针向后一步,当后面一个指针没有后继了,前面一个指针就是要删除的节点注意:可能会出现只有1个节点,同时n=1的情况,这时指针没有后继节点
python代码
# 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 """ """ 采用双指针思想,两个指针相隔n-1,每次两个指针向后一步,当后面一个指针没有后继了,前面一个指针就是要删除的节点 """ p = head q = head Ppre = None for x in xrange(0, n-1): q = q.next while q.next is not None: Ppre = p p = p.next q = q.next # 出现[1],n=1的情况下,Ppre依然为None if Ppre == None: head = p.next else: Ppre.next = p.next return head
相关文章推荐
- 全国各大城市Uber客服联系方式(电话、邮箱、微博)
- Cocoapods安装和使用教程
- 19个MySQL性能优化要点解析
- Exception in thread "http-bio-8080-exec-2" java.lang.OutOfMemoryError: PermGen space[解决方案]
- VHDL快速参考手册
- Java编程之CSV文件导入与导出的实现
- iOS- 指压即达,如何集成iOS9里的3D Touch
- 把二元查找树转变成排序的双向链表
- 正则表达式的基本语法
- 从XML创建的所有Drawable
- SpringMvc配置之<context:annotation-config />
- 自定义view 圆
- Mybatis 获取数据为null
- sql server 复制表结构
- linux编辑器 vi的使用
- 编写你自己的单点登录(SSO)服务
- Node.JS 学习路线图
- 乔治有一些同样长的小木棍。。。
- Pie POJ 3122(二分找最值)
- FZU2150 广搜 两处点火