思路:
先算出链表的长度,减去k就是head需要前进的步数,然后把后面的链表返回即可。
代码(python)实现
# Definition for singly-linked list.
class ListNode:def __init__(self, x):self.val = xself.next = Noneclass Solution:def getKthFromEnd(self, head: ListNode, k: int) -> ListNode:length = 0tempNode = headwhile tempNode != None:length +=1tempNode = tempNode.nextcnt = length-kwhile cnt >0:head = head.nextcnt -=1return head
提交结果:
执行结果:通过执行用时:32 ms, 在所有 Python3 提交中击败了79.59%的用户内存消耗:14.8 MB, 在所有 Python3 提交中击败了83.78%的用户