Stacks and Queues are specialized lists. The special behavior is related to how data gets in and out of the data structure.
Stacks are a "last in first out" datastructure
This means the most recently added item is always the first item to leave the stack.
Imagine a stack of plates
When talking about stacks, programmers use these words to describe specific behavior
Push: add a new item to the top of the stack.
Pop: remove the top item from the stack.
Push
Head
0
1
2
3
Push
Head
0
1
2
3
4
The new node comes on at the head, every thing else is "pushed" down
Pop
Head
0
1
2
3
4
Pop unlinks the top node and puts the head to our new top.
Pop
Head
popped
0
2
3
1
Pop also returns this popped node to the caller.
Pop
Head
popped
0
2
3
1
I think it's interesting that if you push() then pop() you end up with the original stack.
Queues are a "first in first out" data structure.
This means that the first item to get in the queue will always be the first item to come out of the queue.
Queues are a "first in first out" data structure.
Just imagine every line of people you've ever waited in.
When talking about queues, programmers use these words to describe specific behavior
Enqueue: add a new item to the end of the line.
Dequeue: remove the item at the front of the line.
Enqueue
Head
0
1
2
3
Tail
Head
The new node comes on at the head, behind every other node in line
4
Dequeue
Head
0
1
2
3
Tail
Head
The node that has been in the queue longest will be at the tail position. It unlinks and the tail moves back.
4
Dequeue
Head
0
1
2
3
Tail
Head
The dequeued node is returned to the caller.
dequeued
Push, Pop, Enqueue, and Dequeue are all
O(1) or "constant time".
Stacks are important to the way memory is managed, "The Call Stack". It's also a useful model that can be applied to a lot of problems.
Queues are used by the event scheduler in JS. And, like stacks, are a useful model that mimics a lot of real world behavior.