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
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章