Learn
“Enqueue” is a fancy way of saying “add to a queue,” and that is exactly what we’re doing with the enqueue()
method.
There are three scenarios that we are concerned with when adding a node to the queue:
- The queue is empty, so the node we’re adding is both the head and tail of the queue
- The queue has at least one other node, so the added node becomes the new tail
- The queue is full, so the node will not get added because we don’t want queue “overflow”
Let’s put this into action by building out an enqueue()
method for Queue
.
Instructions
1.
Inside the Queue
class you built, define a method enqueue()
that takes a node value value
as a parameter.
- Add an
if
clause to check if the queue has space - If it does, instantiate a
Node
that takesvalue
as its argument and assign it to a new variableitem_to_add
- Print “Adding “ +
str(item_to_add.get_value())
+ “ to the queue!”
2.
Also inside the if
statement, do the following:
- Check if the queue is empty — if so, set both the instance’s
head
andtail
to theitem_to_add
- Otherwise, use
Node
‘sset_next_node()
method to:- set
item_to_add
as the currenttail
‘s next node - set
tail
equal toitem_to_add
- set
- Increment the queue’s
size
by 1
3.
After the outermost if
statement, create an else
statement. Within it, print out “Sorry, no more room!”
Sign up to start coding
By signing up for Codecademy, you agree to Codecademy's Terms of Service & Privacy Policy.