LeetCode#19. Remove Nth Node Fro

作者: 夹小欣 | 来源:发表于2017-11-03 14:25 被阅读6次

一下子就AC了,幸福来的太突然😄

class Solution(object):
    def removeNthFromEnd(self, head, n):
        p = head
        q = head
        count=0
#记录链表的长度
        while(p):
            p = p.next
            count += 1
        if count == 1:
            return None
#找到删除结点的前一个结点
        dele = count-n
        if dele == 0:
            return head.next
        while(dele>1):
            q = q.next
            dele -= 1
#删除结点     
        if q.next: 
            if q.next.next:
                q.next = q.next.next
            else:
                q.next=None
        else:
            return None
        return head

再记录一个以前会过现在忘了,又看到的方法链接

class Solution:
    def removeNthFromEnd(self, head, n):
        fast = slow = head
#找到下标为n-1 的结点,该结点A距离链表尾端的长度是:len(head)-n+1,这个长度刚好是倒数第n个节点的前一个节点的下标,利用这个性质slow可以找到删除节点的前一个节点
        for _ in range(n):
            fast = fast.next
        if not fast:
            return head.next
        while fast.next:
            fast = fast.next
            slow = slow.next
        slow.next = slow.next.next
        return head

相关文章

网友评论

    本文标题:LeetCode#19. Remove Nth Node Fro

    本文链接:https://www.haomeiwen.com/subject/efjtmxtx.html