Return Kth to Last

2.2a Return Kth to Last: Implement an algorithm to find the kth to last element of a singly linked list.

// 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();
}

// recursively

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.

Last updated

Was this helpful?