zoukankan      html  css  js  c++  java
  • Remove Nth Node From End of List

    # 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==None:
                return 
            pre_head=ListNode(0)
            pre_head.next=head
            ruler_end=pre_head
            ruler_head=pre_head
            while n:
                ruler_end=ruler_end.next
                n-=1
            while ruler_end.next!=None :
                ruler_end=ruler_end.next
                ruler_head=ruler_head.next
            temp=ruler_head.next
            ruler_head.next=temp.next
            return pre_head.next

     不知道链表的结尾在哪里的情况下,删除从结尾算起的第n个节点,要求只遍历一趟的情况下完成。

    这道题目确实没想到解决方法,参考别人的。值得记住。

    知道是从结尾算起的第n个节点,那么建立一个距离为n+1的“尺子”,“尺子”的一端到了链表的末尾,那么另一端就是在要删除哪个节点的前一个。

  • 相关阅读:
    深拷贝与浅拷贝
    图片旋转插件
    promise 小抄
    github fork项目更改后与原作者同步更新
    eslint 的配置
    css规范
    Object类
    BigIntager
    System类
    Math类和Random类
  • 原文地址:https://www.cnblogs.com/iois/p/3945536.html
Copyright © 2011-2022 走看看