From the course: Python Data Structures: Stacks, Deques, and Queues

Unlock this course with a free trial

Join today to access over 25,500 courses taught by industry experts.

Stack-based queues

Stack-based queues

- [Instructor] In this video we'll be implementing a stack based queue where the elements are located in two stacks. One for enqueuing and one for dequeuing. Let's start off by defining a class for our queue. We'll call it Queue. So after our class has been defined we add in an init method the initializes two empty lists, enqueue stack and dequeue stack. Next, let's go ahead and define a method to add elements to our queue. This is also known as enqueue. The enqueue method simply adds an item to the end of the list enqueue stack by using the .append keyword. Now, let's define a method which will help us remove elements from the front of our queue. Also, this can be known as dequeue. The dequeue method first checks if the dequeue stack is empty. If it is, then it transfers all the elements from the enqueue stack, the dequeue stack, reversing the order. If the dequeue stack is still empty, it returns…

Contents