前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >leetcode之-题19

leetcode之-题19

作者头像
GavinZhou
发布2018-01-02 15:29:03
3390
发布2018-01-02 15:29:03
举报

题目

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    
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2016-02-18 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 题目
  • 题解
    • 思路
      • python代码
      领券
      问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档