【Python】【难度:简单】Leetcode 1266. 访问所有点的最小时间

实现一种算法,找出单向链表中倒数第 k 个节点。返回该节点的值。

注意:本题相对原题稍作改动

示例:

输入: 1->2->3->4->5 和 k = 2
输出: 4
说明:

给定的 k 保证是有效的。

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/kth-node-from-end-of-list-lcci
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

# Definition for singly-linked list.
# class ListNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution(object):
    def kthToLast(self, head, k):
        """
        :type head: ListNode
        :type k: int
        :rtype: int
        """
        res=[]
        while head:
            res.append(head.val)
            head=head.next
        return res[-k]

执行结果:

通过

显示详情

执行用时 :24 ms, 在所有 Python 提交中击败了67.02%的用户

内存消耗 :12.8 MB, 在所有 Python 提交中击败了100.00%的用户

原创文章 105 获赞 0 访问量 1668

猜你喜欢

转载自blog.csdn.net/thomashhs12/article/details/106041139