You might have come across the terms "stack" and "queue" as two common Abstract Data Structures in programming. For any job interview, it won't be a bad thing to know what these are and when you might want to use them. You might even want to know how to build them!
What are Stacks and Queues
Stacks and queues are quite similar to each other. And it turns out that you can use a linked list as the base for implementing either of these two. Let's start by considering their time complexities for common operations:
These Big-O complexities make both stacks and queues a useful choice for implementing insertion and deletion functionalities. How do the two differ from each other?
Stacks
A stack is a collection where the last item added is the first one you can retrieve from the stack. This is often abbreviated as LIFO, which stands for last in, first out. You can visualize it like a stack of plates:
A stack data structure should implement at least four methods:
- Push adds an element to the collection
- Pop removes the most recently added element from the collection
- Empty checks whether there are any elements in the stack
- Peek returns the topmost element without removing it from the stack
You can implement additional methods, for example, a method that returns the total size of the stack or a method that returns True if the stack is full.
Queues
A queue is a collection where the first item added is the first item that gets removed from the queue. This is often abbreviated as FIFO, which stands for first in, first out. You can think of it just like a queue at the cashier's desk in a supermarket, one of the rare ones where no one skips the line:
A queue data structure should implement at least the following methods:
- Enqueue adds an element to the back of the collection.
- Dequeue removes and returns the element at the front of the queue.
- Empty returns
Trueif the queue is empty, elseFalse. - Peek returns the element at the front of the collection without removing it.
You can implement additional methods, for example, a method that returns the total size of the queue or a method that returns True if the queue is full.
Addition Resources
- Explore CodingNomads Data Structures and Algorithms course
- Learn more about Stacks
- Learn more about Queues
In the next lesson, you'll build a custom queue in Python to continue to train your understanding of Abstract Data Structures.
Summary: Python Queue and Python Stack
- Stacks and Queues are very similar to each other
- Stacks are a collection where the last item added is the first one you can retrieve from the stack
- LIFO stands for last in, first out
- Queues are a collection where the first item added is the first item that gets removed from the queue
- FIFO stands for first in, first out
Required Methods for a Stack
- Push $`0(1)`$
- Pop $`0(1)`$
- Empty $`0(1)`$
- Peek $`0(1)`$
Required Methods for a Queue
- Enqueue $`0(1)`$
- Dequeue $`0(1)`$
- Empty $`0(1)`$
- Peek $`0(1)`$