Leetcode刷题记录——面试题 02.02. 返回倒数第 k 个节点
程序员文章站
2024-03-04 10:16:29
...
设置两个指针
start和res
start先出发,走k-1次
此后,start和res一起后移 直至start为队尾 res即为所求
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def kthToLast(self, head: ListNode, k: int) -> int:
start = head
res = head
for i in range(k-1):
start = start.next
while start.next is not None:
start = start.next
res = res.next
return res.val