1、双指针
我们先让一个指针faster走k步,再让两个指针slower和faster一起移动直至faster走到末端为止。
class Solution {
public:
ListNode *getKthFromEnd(ListNode *head, int k) {
ListNode *slower = head, *faster = head;
for (int i = 0; i < k; ++i) {
faster = faster->next;
}
while (faster!= nullptr){
faster=faster->next;
slower=slower->next;
}
return slower;
}
};