Skip to Content
Learn
Linked Lists: Python
Linked Lists Implementation II

So far we can:

  • create a new LinkedList using .__init__()
  • get the head node of the list using .get_head_node()

Next up, we’ll define methods for our LinkedList class that allow us to:

  • insert a new head node
  • return all the nodes in the list as a string so we can print them out in the terminal!

Instructions

1.

Define an .insert_beginning() method which takes new_value as an argument.

  • Inside the method, instantiate a Node with new_value. Name this new_node.
  • Now, link new_node to the existing head_node.
  • Finally, replace the current head_node with new_node.

Note: Because the workspace is set up with spaces instead of tabs, you will need to use spaces to prevent Python from throwing an error. You can learn more about this here.

2.

Define a .stringify_list() method we can use to print out a string representation of a list’s nodes’ values.

The method should traverse the list, beginning at the head node, and collect each node’s value in a string. Once the end of the list has been reached, the method should return the string.

You can use str() to convert integers to strings!

Be sure to add "\n" between values so that each value prints on a new line.

3.

Test your code by uncommenting the print statement at the bottom of script.py — did your list print what you expected?

Folder Icon

Sign up to start coding

Already have an account?