To implement a stack or a queue, we can use the array object and its method without any changes. However, we will create separate objects which will use the array object to define custom functions.
A stack works on the principle “Last In First Out (LIFO)”. Its implementation in real life is simple and, stacks are around us every day. Think of the pile of books kept on your desk or a deck of card with a rule that you can pick a book or a card from the top.
And that’s the difference between a stack (or a queue) and an array. In an array, we can randomly access elements at any of the indices.
Let’s see the implementation of a stack using an array.
We have used the plain array inside the constructor function. Wrapping everything inside a custom object prevents the random access of elements from the array/stack.
The implementation of a queue is not a lot different from the stack.
A queue works on “First In First Out (FIFO)”. I am sure I don’t need to give an example of a queue. So let’s jump to the implementation part.