I guess that you are talking about "program stack" |
Yes. But not only!
There may be other implementations of a "stack" data structures that, too, allow you to access elements in the "middle" of the stack.
For example, in Java, the
Stack
class actually
extends the
Vector
class. And the
Vector
class has a
get()
method to get elements
by index. Consequently, since Java's
Stack
class is derived from the
Vector
class, the
Stack
class exposes the
get()
method too! In other words, we can use
push()
and
pop()
to add or remove elements, but we can also access
all existsing elements
by index via the
get()
method.
Example:
https://pastebin.com/nh9YUAAQ
https://pastebin.com/BZK6fyaK
If this is the case, why is it actually considered a stack and not array? |
Because a "stack" is an
abstract data type.
There are many different ways how a "stack" can be
implemented, and the details of different implementations differ!
Using an
array is actually
one common way to implement a "stack" data structure:
https://en.wikipedia.org/wiki/Stack_(abstract_data_type)#Array 😏
In other words, a (bounded-size) "stack"
may be thought of as an
array that has an additional variable (counter) in order to keep track of the index of the current "top" element, so that the
push()
and
pop()
operations can be implemented with the usual "stack" semantics.
BTW: Implementing a "stack" as a
linked-list is a possible alternative to using an array. There may be others!
And I guess that in stack data type u cannot access the middle of the stack |
Totally depends on the concrete
implementation !!!
With C++'s
std::stack
you can
not access elements in the "middle". At least not without deriving your own sub-class 😏
But, with Java's
Stack
class, for example, you
can access arbitrary elements
by index. See my example above!
Python has
no dedicated "stack" type, but a normal Python
list supports
pop()
to remove and return its last element. Thus, you can use a Python
list as a "stack" via the
append()
and
pop()
methods, but of course you may also access
any element
by its index.