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
posted @ 2020-05-09 13:46  人间烟火地三鲜  阅读(141)  评论(0编辑  收藏  举报