Learn
The stack’s push()
and pop()
methods are our tools to add and remove items from it. pop()
additionally returns the value of the item it is removing. Keep in mind that we can only make modifications to the top of the stack.
Instructions
1.
Below __init__()
, define a method push()
for Stack
that takes the parameter value
. Inside the method:
- Instantiate a
Node
withvalue
as an argument and assign it to the variableitem
(because this item is a node, we have easy access to Node’s class methods) - Set
item
‘s next node to the stack’s currenttop_item
using theNode
methodset_next_node()
- Set the stack instance’s
top_item
equal to the new item, adding it to the top of the stack
2.
Below push()
, define a method pop()
for Stack
. Inside pop()
:
- Create a variable
item_to_remove
and set it equal to the stack’stop_item
- If we’re removing our stack’s
top_item
, we need to set a newtop_item
! Set thetop_item
equal to the node afteritem_to_remove
- Return the
value
stored initem_to_remove
Sign up to start coding
By signing up for Codecademy, you agree to Codecademy's Terms of Service & Privacy Policy.