题目:
思路:
快慢指针,快指针先走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