Skip to content

Stacks and Queues

Billy Bunn edited this page Mar 29, 2019 · 2 revisions

Intro

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.

Stacks

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.

Queues

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.

Resources

Read:

Clone this wiki locally