題目
https://www.lintcode.com/problem/nth-to-last-node-in-list/description?_from=ladder&&fromId=2
實現
- 設置兩個指針,fast 指針先走 n 步
- 然後兩個指針再同時走,走到 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