19. 删除链表的倒数第N个节点



思路:

快慢指针,间隔n+1,当fast为None时,断掉slow.next:slow.next = slow.next.next。

class Solution(object):
    def removeNthFromEnd(self, head, n):
        """
        :type head: ListNode
        :type n: int
        :rtype: ListNode
        """
        ans = ListNode(0)
        ans.next = head
        slow, fast = ans, ans
        while n:
            fast = fast.next
            n -= 1
        while fast.next:
            slow = slow.next
            fast = fast.next
        # slow.next即是倒数第n个节点
        slow.next = slow.next.next
        return ans.next
原文地址:https://www.cnblogs.com/panweiwei/p/12856968.html