DEV Community

Brittany Javalera
Brittany Javalera

Posted on

Data Structures- Pt 1: Stacks and Queues

I had tried learning about data structures on my own by reading through many articles and watching tutorials but the concepts never quite stuck. I decided to ask for recommendations from fellow bootcamp grads and most of them suggested a few courses on Udemy. I am in the middle of one of those courses and I can happily say that I am finally understanding the concepts! In my next few post I will be sharing what I have learned.

Data structures are ways of organizing information with optimal runtime for adding, editing, and removing data.

Queues

A queue is ordered list, using first-in/first-out list management. You can compare it to standing in line at the meat counter at the grocery. You take a number(index), and the butcher will call the numbers in order starting from smallest to largest, so the first person to get a ticket will be the first person called, and so on.

  • Adding a record to a queue(a new person getting in like), is called enqueuing.
  • Dequeuing is removing the first record of the queue(the first person in line has completed their transaction and leaves).

Stacks

Stacks are also ordered lists but use first-in/last-out order list management. The concept is the same as stacking plates on a shelf. The first plate you place on the shelf becomes plate on the bottom and last plate you place on the shelf is at the top. So, when you grab to plate on top for your next meal, you are taking the last plate you put the shelf.

In Javascript, arrays are used for both Queues and Stacks but with limitations.

  • For Queues we use can use .unshift() to add to the the array, and .pop() to remove from the other end.
  • For Stacks we use .push to add to the end and .pop() to remove the last item.

Adding and removing are the main operations for these data structures but we can also create a peek function to preview the record at the front of a queue, or last/"top" of a stack.
We can also combine multiple queues into one queue and create a queue from stacks.

Top comments (0)