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:
- The queue is empty, so we cannot remove or return any nodes lest we run into queue “underflow”
- The queue has one node, so when we remove it, the queue will be empty and we need to reset the queue’s
head
andtail
toNone
- The queue has more than one node, and we just remove the
head
node and reset thehead
to the following node
Instructions
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 currenthead
- Inside your
if
statement, print: “Removing “ +str(item_to_remove.get_value())
+ “ from the queue!”
Inside the if
statement, below your print statement, check if the size
is 1.
- If so, give the queue’s
head
andtail
a value ofNone
- Otherwise, set the queue’s
head
equal to the following node usingNode
‘s handy dandyget_next_node()
method
Outside of the inner if
/else
clause
- reduce the queue’s
size
by 1 - use
Node
‘sget_value()
method to return the value ofitem_to_remove
After the outermost if
statement, create an else
statement. Within it, print “This queue is totally empty!”