1. 程式人生 > >python---連結串列倒數第n個節點

python---連結串列倒數第n個節點

"""
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

        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