剑指offer 15. 链表中倒数第k个结点

原题

输入一个链表,输出该链表中倒数第k个结点。

Reference Answer

解题思路:

对于这种python求解链表题,尤其是本题让返回节点或者值,直接先遍历玩链表转换到 python 的list中,再进行操作,顺风顺水。

# -*- coding:utf-8 -*-
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:
    def FindKthToTail(self, head, k):
        # write code here
        
        res = []
        while head:
            res.append(head)
            head = head.next
        if k > len(res) or k < 1:
            return None
        else:
            return res[-k]

猜你喜欢

转载自blog.csdn.net/Dby_freedom/article/details/83214390