前言
依旧力扣,这道题之前有做过类似的题,今天给一个新的思路去做,应对面试时候遇到的奇奇怪怪的问题
面试题 02.02. 返回倒数第 k 个节点 - 力扣(LeetCode)
https://leetcode.cn/problems/kth-node-from-end-of-list-lcci/description/
这道题如果只遍历一次数组,我们该怎么做 呢
一,思路
我们依旧创建快慢指针,只不过这次不是谁比谁走的快,而是快指针比慢指针提前走了 k 步

二,代码实现
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
int kthToLast(struct ListNode* head, int k){
struct ListNode *fast = head, *slow =head;
//快指针走k步
while(k--){
fast = fast->next;
}
//同时走
while(fast){
slow = slow->next;
fast = fast->next;
}
return slow->val;
}
要注意题干条件最终返回值 val ,如果直接返回 slow 会报错













![[数据集][目标检测]道路井盖下水道井盖开关闭和检测数据集VOC+YOLO格式407张2类别](https://img-blog.csdnimg.cn/direct/741132d6defa432384a76daeb1b1028d.png)
![[图解]企业应用架构模式2024新译本讲解02-表数据入口](https://img-blog.csdnimg.cn/direct/99e98b6fbe7749c2a5e8dc7be4d38bd1.png)




