Stacks and Queues in Python

python_tutorials

Introduction

Data structures organize storage in computers so that we can efficiently access and change data. Stacks and Queues are some of the earliest data structures defined in computer science.

Simple to learn and easy to implement, their uses are common and you’ll most likely find yourself incorporating them in your software for various tasks.

It’s common for Stacks and Queues to be implemented with an Array or Linked List. We’ll be relying on the List data structure to accommodate both Stacks and Queues.

How do they Work?

Stack

Stacks, like the name suggests, follow the Last-in-First-Out (LIFO) principle. As if stacking coins one on top of the other, the last coin we put on the top is the one that is the first to be removed from the stack later.

To implement a stack, therefore, we need two simple operations:

  • push – adds an element to the top of the stack:

Adding an item to a stack

  • pop – removes the element at the top of the stack:

Removing an item from a stack

Queue

Queues, like the name suggests, follow the First-in-First-Out (FIFO) principle. As if waiting

To finish reading, please visit source site