Node * kthtolast2(Node *head, int k,int &count) {
if (!head) return nullptr;
Node *temp = kthtolast2(head->next, k, count);
++count;
if (count - 1 == k) {
return head;
}
return temp;
}
int kthtolast(Node *head, int k) {
int count = 0;
Node *ret = kthtolast2(head, k, count);
if (!ret) return INT_MIN;
return ret->value;
pause();
}
2.2b Remove jth to Last: Implement an algorithm that removes the jth to last element in a linked list.
The approach I took with this can also be used for 2.2a. The idea is that if you increment one point j amount of times, and have a second point start from the first while iterating both to the end, when the first pointer stops will be when the second pointer is at j.