Return Kth to Last
// simulating recursive operation
int kthtolast(Node *head, int k) {
stack<Node*> s;
Node *iter = head;
s.push(iter);
while (iter) {
s.push(iter->next);
iter = iter->next;
}
s.pop(); // remove null
int count = 0;
while (count < k) {
count++;
s.pop();
if (s.empty()) {
return INT_MIN;
}
}
return s.top()->value;
}
int main()
{
LinkedList LL1;
srand(time(nullptr));
int counter = 0;
int random;
while (counter <= 100) {
random = rand() % 1000 + 2;
LL1.insert(random);
counter++;
}
LL1.print();
cout << LL1.kthtolast(LL1.front, 1) << endl;
cout << LL1.kthtolast(LL1.front, 0) << endl;
cout << LL1.kthtolast(LL1.front, 10) << endl;
cout << LL1.kthtolast(LL1.front, 1000) << endl;
pause();
}Last updated