-
Notifications
You must be signed in to change notification settings - Fork 0
Stacks and Queues
Stacks and queues are both data structures made up of nodes. Each node in these structures has a next
property that is a reference to the next node in the structure's sequence. How these nodes are organized and how nodes are added or removed is different depending on the data structure.
In a stack, the nodes follow LIFO (Last In, First Out), meaning the last node to be added to the stack (or pushed) will be the first node that can be removed from the stack (or popped).
It's as simple as a stack of plates for a dishwasher; the first plate to be cleaned will always be the plate on the top of the stack.
The first node in the stack is called the Top
. The last node in a stack has a next
property of null
. It's good to check the top of the stack (or peek) to see if the stack isn't empty.
In a queue, the nodes follow FIFO (First In, First Out) and LILO (Last In, Last Out), meaning the nodes flow from beginning to end (or rear to front). When you add a node to a queue (or enqueue), the node goes to the rear of the queue. When you remove a node from a queue (or dequeue), the node comes from the front of the queue.
Think of a line at a grocery store or an amusement park ride. Every person has to wait their turn and flow from the back of the line to the front.
When you enqueue and dequeue, you have to change the references of the rear
and front
.
All wiki pages are summaries of the work of others. See the top of each page for the source blogs/articles/books and their authors. All other content by Billy Bunn.