题意:删除链表中倒数第n个结点,尽量只扫描一遍。 使用两个指针扫描,当第一个指针扫描到第N个结点后, 第二个指针从表头与第一个指针同时向后移动, 当第一个指针指向空节点时,另一个指针就指向倒数第n个结点了 ‘’’
""" Definition of ListNode class ListNode(object): def __init__(self, val, next=None): self.val = val self.next = next """ class Solution: """ @param head: The first node of linked list. @param n: An integer @return: The head of linked list. """ def removeNthFromEnd(self, head, n): # write your code here fast = head while n > 1: fast = fast.next n = n -1 slow = head pre = None while fast.next: pre = slow fast = fast.next slow = slow.next if pre: #判断删除的点是不是head节点,如果进入了上一个while循环,则不是head节点。 pre.next = slow.next else: head = head.next return head