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

  • 记住,return的时候return dummy.next 而不是head,无论什么情况
    def removeNthFromEnd(self, head, n):
        """
        :type head: ListNode
        :type n: int
        :rtype: ListNode
        """
        if not head:
            return head

        dummy = ListNode(-1)
        dummy.next = head
        cur = dummy
        pre = dummy
        for i in range(n + 1):
            try:
                cur = cur.next
            except:
                return head
        while cur:
            cur = cur.next
            pre = pre.next
        pre.next = pre.next.next
        
        # 记住,return的时候return dummy.next 而不是head,无论什么情况
        return dummy.next

你可能感兴趣的:(19. 删除链表的倒数第 N 个节点)