Array vs Stack – Differences Explained

arraydata structuresstack

According to Wikipedia, a stack:

is a last in, first out (LIFO) abstract data type and linear data structure.

While an array:

is a data structure consisting of a collection of elements (values or variables), each identified by at least one array index or key.

As far as I understand, they are fairly similar. So, what are the main differences? If they are not the same, what can an array do that a stack can't and vice-versa?

Best Answer

Well, you can certainly implement a stack with an array. The difference is in access. In an array, you have a list of elements and you can access any of them at any time. (Think of a bunch of wooden blocks all laid out in a row.)

But in a stack, there's no random-access operation; there are only Push, Peek and Pop, all of which deal exclusively with the element on the top of the stack. (Think of the wooden blocks stacked up vertically now. You can't touch anything below the top of the tower or it'll fall over.)

Related Topic