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

题目:

思路:

快慢指针,快指针先走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

相关问题

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