• 为了保证你在浏览本网站时有着更好的体验,建议使用类似Chrome、Firefox之类的浏览器~~
    • 如果你喜欢本站的内容何不Ctrl+D收藏一下呢,与大家一起分享各种编程知识~
    • 本网站研究机器学习、计算机视觉、模式识别~当然不局限于此,生命在于折腾,何不年轻时多折腾一下

leetcode–Remove Nth Node From End of List

leetcode admin 2年前 (2017-04-13) 1045次浏览 0个评论 扫描二维码

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.

# 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 
        """ 
        ncount=0 
        rhead=phead=head 
        while ncount<n: 
            head=head.next 
            ncount+=1 
        if not head: 
            return rhead.next 
        while head.next: 
            phead=phead.next 
            head=head.next 
  
        phead.next=phead.next.next 
         
        return rhead

Deeplearn, 版权所有丨如未注明 , 均为原创丨本网站采用BY-NC-SA协议进行授权 , 转载请注明leetcode–Remove Nth Node From End of List
喜欢 (0)
admin
关于作者:
互联网行业码农一枚/业余铲屎官/数码影音爱好者/二次元

您必须 登录 才能发表评论!