Stacks vs Queues
What is the difference between a stack data structure and a queue data structure?
A Queue is a FIFO (First In — First Out) algorithm. That means that the value that was inserted first will be the first one to come out. For instance, if you have the following list in python:
[1,2,3,4,5]
1 is the front of the queue. If you append another value, it will go to the back of the queue, for instance:
[1,2,3,4,5,6]
Whereas if you want to retrieve a value, it will be the first element 1 that will be returned first.
Whereas with stacks, this is a LILO (Last in — last out) algorithm. This means that each new value that is added to the list will be the first one to be popped off. For instance:
[1,2,3,5,6,7]
If we go with the stack approach, if we wanted to insert a new value, it would be appended to the end, like so:
[1,2,3,4,5,6,7,8]
However, if we wanted to retrieve a value, unlike with queues, it would be the last value that was inserted that would be returned, in our case that would be the value 8.