python---链表倒数第n个节点

来源:互联网 发布:哼歌识曲的软件 编辑:程序博客网 时间:2024/06/04 19:07
"""Definition of ListNodeclass 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        tem = head        num_tem =n        if not head:            return None        while tem and num_tem>1:            tem = tem.next            num_tem-=1        tem_n = tem        head_n = head        while tem_n.next :            tem_n = tem_n.next            head_n = head_n.next        return head_n