Search code examples
stack

Do stacks have indexes?


Yeah, so one of my friends said we can use indexes to traverse a stack, but I think he's wrong. Basically, I have a homework in which I had to write an algorithm using an array. I had to use two for loops to do it, so I was wondering how to do something like this with a stack:

for(int i = 0; i < n; i++)
{
    for(int j = 0; j < n; j++)
    {
        x = A[i]+A[j]
    }
}

There is no way right? And I have to use pop() and push() only to do whatever I need to do, right? Because I used an array and stack concurrently, but one of my friends told me I can't do that. I know we can implement a stack using an array, but the stack ADT doesn't have indexes (although they just said stack and not stack ADT).


Solution

  • said we can use indexes to traverse a stack, but I think he's wrong.

    You're right, he's wrong.

    There is no way [to do two nested loops] right?

    You can access element at index if you have enough space for a temporary stack: pop to the index while storing the popped values onto a temp stack, remember the value, and then push the values back:

    int GetAt(Stack s, int index) {
        Stack temp;
        while (temp.size() != index) {
            temp.push(s.pop());
        }
        int res = temp.top();
        while (!temp.empty()) {
            s.push(temp.pop());
        }
        return res;
    }
    

    Yes, that's very, very slow.