找到单链表倒数第 n 个节点,保证链表中节点的最少数量为 n
参考代码:
class ListNode(object): def __int__(self, val): self.val = val self.next = None class Solution: def nthToLast(self, head, n): if head is None or n < 1: return None cur = head.next while cur is not None: cur.pre = head cur = cur.next head = head.next n -= 1 while n > 0: head = head.pre n -= 1 return head