166. Nth to Last Node in List

题目

https://www.lintcode.com/problem/nth-to-last-node-in-list/description?_from=ladder&&fromId=2

实现

  1. 设置两个指针,fast 指针先走 n 步
  2. 然后两个指针再同时走,走到 fast 指针走到尽头,slow 指针就是倒数第 n 个元素

代码

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: Nth to last node of a singly linked list.
    """
    def nthToLast(self, head, n):
        if head is None or head.next is None:
            return head

        slow = head
        fast = head

        for i in range(n):
            fast = fast.next

        while fast is not None:
            slow = slow.next
            fast = fast.next

        return slow

你可能感兴趣的:(166. Nth to Last Node in List)