zoukankan      html  css  js  c++  java
  • 边工作边刷题:70天一遍leetcode: day 38-2

    Remove Nth Node From End of List

    要点

    • first和second指针的距离:n是从1开始计数的,所以second指向的node和被删的node之间共n个node(包括这两个边界node)。first指向被删node的前一个,这样才能进行list node的删除
    • 根据上面的距离关系,first开始指向dummy,second要首先从head开始单独移动n-1步,之后移动second到最后一个node,这样first.next指向被删node。所以用second.next!=null作为循环条件
    # 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
            """
            dummy = ListNode(0)
            dummy.next = head
            first, second = dummy, head
            while second.next and n>1:
                second=second.next
                n-=1
            
            if n!=1:
                return None
            
            while second.next:
                first=first.next
                second=second.next
                
            first.next=first.next.next
            return dummy.next
                
                
                
                
    
  • 相关阅读:
    加深对C#数据类型的认识
    Spring------关于代理
    Java数组
    C#小型资源管理器
    面向对象七大原则
    关于C#换肤IrisSkin
    非泛型集合
    经理评价系统总结
    深入.NET框架
    航班系统总结
  • 原文地址:https://www.cnblogs.com/absolute/p/5678280.html
Copyright © 2011-2022 走看看