Function to find number of elements in a stack

How do you write a function that would show how many elements are in the stack?

And also what is an arithmetic expression that would compute the number of elements given the value of top?
Last edited on
Depends on what information you're allowed to access. Assuming you don't simply have a "size" data member, you'd have to copy the stack, and then every time you pop from this copied stack, increase a size variable by one. Once the copied stack is empty, return the summed size, leaving the original stack untouched.

Your second question doesn't make any sense, sorry. A stack is an Abstract Data Type that can hold more than just pure numbers, and even if it was a stack of ints, the top value is independent from other values.
Topic archived. No new replies allowed.