LintCode 166 [Nth to Last Node in List]

原题

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

样例
给出链表** 3->2->1->5->null**和n = 2,返回倒数第二个节点的值1.

解题思路

  • 快慢指针, 快指针先走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: Nth to last node of a singly linked list. 
    """
    def nthToLast(self, head, n):
        # write your code here
        if not head:
            return head
        
        slow, fast = head, head
        for _ in range(n):
            fast = fast.next
        
        while fast != None:
            slow = slow.next
            fast = fast.next
        
        return slow

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