【LeetCode】面试题22. 链表中倒数第k个节点
题目:
![](https://img2020.cnblogs.com/blog/784062/202006/784062-20200601181320235-1635819594.png)
思路:
快慢指针,快指针先走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