题目描述
思路分析
链表模拟题
遍历两边即可。
代码实现
/**
* struct ListNode {
* int val;
* struct ListNode *next;
* ListNode(int x) : val(x), next(nullptr) {}
* };
*/
class Solution {
public:
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param pHead ListNode类
* @param k int整型
* @return ListNode类
*/
ListNode* FindKthToTail(ListNode* head, int k) {
int cnt=0;
auto a=head;
while(a) cnt++,a=a->next;
if(cnt<k) return NULL;
a=head;
for(int i=1;i<=cnt-k;i++) a=a->next;
return a;
}
};