首页 > 其他 > 详细

【LeetCode】面试题22. 链表中倒数第k个节点

时间:2020-06-01 18:29:37      阅读:40      评论:0      收藏:0      [点我收藏+]

题目:

技术分享图片

思路:

快慢指针,快指针先走k步,然后快慢指针一起走。

代码:

Python

# 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
        """
        if head is None:
            return None
        end = head
        while k:
            if end is None:
                return None
            end = end.next
            k -= 1
        while end:
            head = head.next
            end = end.next
        return head

相关问题

【LeetCode】面试题22. 链表中倒数第k个节点

原文:https://www.cnblogs.com/cling-cling/p/13026604.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!