Learn

We can add items to the tail of our queue, but we remove them from the head using a method known as dequeue(), which is another way to say “remove from a queue”. Like enqueue(), we care about the size of the queue — but in the other direction, so that we prevent queue “underflow”. After all, you don’t want to remove something that isn’t there!

As with peek(), our dequeue() method should return the value of the head. Unlike, peek(), dequeue() will also remove the current head and replace it with the following node.

For dequeue, there are three scenarios that we will take into account:

  1. The queue is empty, so we cannot remove or return any nodes lest we run into queue “underflow”
  2. The queue has one node, so when we remove it, the queue will be empty and we need to reset the queue’s head and tail to None
  3. The queue has more than one node, and we just remove the head node and reset the head to the following node

Instructions

1.

Inside the Queue class you built, define a method dequeue().

  • Add an if clause to check if the queue is not empty
  • If so, set a new variable item_to_remove to the current head
  • Inside your if statement, print: “Removing “ + str(item_to_remove.get_value()) + “ from the queue!”
2.

Inside the if statement, below your print statement, check if the size is 1.

  • If so, give the queue’s head and tail a value of None
  • Otherwise, set the queue’s head equal to the following node using Node‘s handy dandy get_next_node() method
3.

Outside of the inner if/else clause

  • reduce the queue’s size by 1
  • use Node‘s get_value() method to return the value of item_to_remove
4.

After the outermost if statement, create an else statement. Within it, print “This queue is totally empty!”

Sign up to start coding

Mini Info Outline Icon
By signing up for Codecademy, you agree to Codecademy's Terms of Service & Privacy Policy.

Or sign up using:

Already have an account?