【Python】【难度:简单】Leetcode 面试题22. 链表中倒数第k个节点

输入一个链表,输出该链表中倒数第k个节点。为了符合大多数人的习惯,本题从1开始计数,即链表的尾节点是倒数第1个节点。例如,一个链表有6个节点,从头节点开始,它们的值依次是1、2、3、4、5、6。这个链表的倒数第3个节点是值为4的节点。

示例:

给定一个链表: 1->2->3->4->5, 和 k = 2.

返回链表 4->5.

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/lian-biao-zhong-dao-shu-di-kge-jie-dian-lcof
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

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

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

执行结果:

通过

显示详情

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

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

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

猜你喜欢

转载自blog.csdn.net/thomashhs12/article/details/106041253
今日推荐