Log in from a computer to take this course

You'll need to log in from a computer to start Linear Data Structures. But you can practice or keep up your coding streak with the Codecademy Go app. Download the app to get started.

apple storegoogle store
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 with value as an argument and assign it to the variable item (because this item is a node, we have easy access to Node’s class methods)
  • Set item‘s next node to the stack’s current top_item using the Node method set_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’s top_item
  • If we’re removing our stack’s top_item, we need to set a new top_item! Set the top_item equal to the node after item_to_remove
  • Return the value stored in item_to_remove

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?