Nth to Last Node in List
Example
Solution
"""
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
fast = head
slow = head
start = 0
while fast and n > start:
fast = fast.next
start = start + 1
while fast and slow:
fast = fast.next
slow = slow.next
return slowLast updated