A stack is another data structure which is used by developers. Like a queue, it can be built off of a linked list data structure or an array. However, in many ways, it is the opposite of a Queue in the way it processes itself.
A stack works Last In, First Out (LIFO) – either way, it works the same. The last item added to the stack, will be the first one removed. That means the first item added, will remain the longest amount of time in the stack.
Stacks in Real Life
A real world physical example where you would see a stack is in a cafeteria where you pick plates from a stack of plates. As new plates come out, they are put on top, where dinners grab from the top. You only get to the end if no new plates are coming out.
How a Stack Works
When working with a stack you start initially with an empty stack. The first item is then placed on the stack.
The Push Method
As items are added, the newest item is placed in front of the previous items. This operation is referred to as a push
, as you could think of pushing the existing items down the line so they are used after the newest item.
The Pop Method
When an element is needing to be removed, you remove the top element, and the next element becomes the top element. That will be the next to be used and removed. This process is called a pop
. You need to verify that there is an item on the stack before you attempt to pull it off and remove it for use. For that, you can use the following isEmpty method, or something similar.
Utility Methods
To assist with working with stacks, most libraries have an isEmpty()
method which can be used to check to see if there are any elements currently on the stack. They will also often have a top() method to find the value of the top most element, without having to remove that item from the stack.
A downside of the stack is that since you are removing the most recent elements first, you could run into a situation where you never get to the bottom of the stack in some instances.
In some simple cases, if you know you won’t have many items, you can use an array, and store the index variable to move it up and down. This is fairly rare, as it won’t let you grow beyond the size of the array.
An Introduction to Stacks was originally found on Access 2 Learn