每日一题 【每日一题】链表倒数第 n 个节点-Python-20211105

Jack · 2021年11月05日 · 最后由 Jack 回复于 2021年11月06日 · 40 次阅读
本帖已被设为精华帖!

找到单链表倒数第 n 个节点,保证链表中节点的最少数量为 n

Jack 将本帖设为了精华贴 11月05日 22:33

参考代码:

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
需要 登录 后方可回复, 如果你还没有账号请点击这里 注册