链接:19. 删除链表的倒数第 N 个结点 - 力扣(LeetCode)
直接写
1 # Definition for singly-linked list. 2 # class ListNode(object): 3 # def __init__(self, val=0, next=None): 4 # self.val = val 5 # self.next = next 6 class Solution(object): 7 def removeNthFromEnd(self, head, n): 8 """ 9 :type head: Optional[ListNode] 10 :type n: int 11 :rtype: Optional[ListNode] 12 """ 13 length = 0 14 currNode = head 15 while currNode: 16 length += 1 17 currNode = currNode.next 18 if length == n: 19 return head.next 20 n = length - n 21 currNode = head 22 if n == 0: 23 return None 24 while n > 1: 25 currNode = currNode.next 26 n -= 1 27 currNode.next = currNode.next.next 28 return head 29 30