1.问题描述:
找到单链表倒数第n个节点,保证链表中节点的最少数量为n。
2.样例:
给出链表 3->2->1->5->null和n = 2,返回倒数第二个节点的值1。
此题样例描述有误,应该返回倒数第n个结点。
3.代码:
"""
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 head is None or n==0:
return None
count=0
pre=head
while pre:
count+=1
pre=pre.next
m=count-n
while m:
head=head.next
m-=1
return head