19. 删除链表的倒数第N个节点 快慢指针变体运用

删除倒数节点

题目需要一次扫描,那么需要用到快慢指针。
删除倒数第n个节点,那么让快指针先走n步即可;注意边界条件,当被删除的节点为头结点时应单独分析

# Definition for singly-linked list.
# class ListNode(object):
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution(object):
    def removeNthFromEnd(self, head, n):
        """
        :type head: ListNode
        :type n: int
        :rtype: ListNode
        """
        fast = slow = head
        while n != 0:
            fast = fast.next 
            n -= 1

        # fast为空 删除头结点
        if fast == None:
            return head.next

        while fast != None and fast.next != None:
            fast = fast.next 
            slow = slow.next

        slow.next = slow.next.next 

        return head 

链表操作

快慢指针有多种形式:

  • 倍数差值可找二分点
  • 固定差值可找倒数第几个点