链表倒数第n个节点
2018-04-25 本文已影响9人
只为此心无垠
链表倒数第n个节点
找到单链表倒数第n个节点,保证链表中节点的最少数量为n。
题目地址
注意点:
1、dummy_node
2、n超出范围
def nthToLast(self, head, n):
# write your code here
if n <= 0:
return None
dummuy_node = ListNode(0)
dummuy_node.next = head
fast = dummuy_node
while n > 0 and fast:
fast = fast.next
n -= 1
if n == 0:
slow = dummuy_node
while fast:
fast = fast.next
slow = slow.next
return slow
else:
return None