Queues vs. Stacks - A brief visual explanation
A queue is a FIFO (first-in-first-out) data structure while a stack is a LIFO (last-in-first-out) data structure.What is a queue?
A queue holds a collection of objects where the newest object is added to the back and the oldest object is removed from the front.
Like a queue at the bank
The queue data structure works just like a queue of people in line at a bank. The first person to get in line is first to leave (i.e., first-in-first-out). The last person in the line will be the last to leave.
Common methods:
Enqueue
= Insert an object at theback
of the queueDequeue
= Delete an object from thefront
of the queuePeek
= Look at the item at the front
Common terminology:
Front
= Oldest item in the collectionBack
= Newest item in the collection
Queue Visualization
Queue
Queues are FIFO (first-in-first-out) data structures. Enqueue on the rear, dequeue on the front.
Queue output:
Sequence: [1] > [1,2] > [2] > [2,3] > [2,3,4] > [3,4]
Most languages have highly performant built-in queues
The above queue code is just for illustration purposes and to keep it simple we used a standard list.
You would most likely wish to use collections.deque
or queue.Queue
instead of rolling your own queue class.
What is a stack?
A stack holds a collection of objects that are inserted and removed from the top of the stack.
Common methods:
Push
= Insert an object at the top of the stackPop
= Remove an object from the top of the stack and return itPeek
= Look at the top object without modifyingisEmpty
= Check if stack is empty
Common terminology:
Top
= The newest item in the collection. Pushing, popping, and peeking all affect the top element.
Stack Visualization
Stack
Stacks are LIFO (last-in-first-out) data structures. Add on the top, remove from the top.
Stack output
Sequence: [1] > [2,1] > [1] > [3,1]
Most languages have a built-in stack module
As with the note about queues above, this code is merely for illustrative purposes and uses a list. In the real world, you would likely either use collections.deque
, or queue.LifoQueue
for more performant appending.