定义两个指针,开始时都位于头节点,先让其中的一个指针先走,使得两个指针之间的节点各位为k,这时就同时移动两个指针。
/**
* 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* pHead, int k) {
ListNode* pre = pHead, *cur = pHead;
int count = 0;
while (cur != NULL) {
if (count != k) {
count++;
} else {
pre = pre->next;
}
cur = cur->next;
}
if (count != k) return NULL;
else
return pre;
}
};