只遍历链表一次的做法: 双指针算法。
第一个指针先走k-1步,从第k步开始,第二个指针也开始和第一个指针同步走。两个指针距离保持k-1,第一个指针走到尾节点时,第二个就刚好到了倒数第k个节点上。
class Solution {
public:
int kthToLast(ListNode* head, int k) {
if(head == nullptr) return 0;
ListNode* curI = head;
ListNode* curJ = head;
int cnt = 0;
for(int i = 0; i < k -1; i++){
if(curJ->next != nullptr) curJ = curJ->next;
}
while(curJ->next != nullptr){
curI = curI->next;
curJ = curJ->next;
}
return curI->val;
}
};