FAQ: Linked Lists: Python - Linked List Review

This community-built FAQ covers the “Linked List Review” exercise from the lesson “Linked Lists: Python”.

Paths and Courses
This exercise can be found in the following Codecademy content:

Computer Science

Linear Data Structures

FAQs on the exercise Linked List Review

There are currently no frequently asked questions associated with this exercise – that’s where you come in! You can contribute to this section by offering your own questions, answers, or clarifications on this exercise. Ask or answer a question by clicking reply (reply) below.

If you’ve had an “aha” moment about the concepts, formatting, syntax, or anything else with this exercise, consider sharing those insights! Teaching others and answering their questions is one of the best ways to learn and stay sharp.

Join the Discussion. Help a fellow learner on their journey.

Ask or answer a question about this exercise by clicking reply (reply) below!

Agree with a comment or answer? Like (like) to up-vote the contribution!

Need broader help or resources? Head here.

Looking for motivation to keep learning? Join our wider discussions.

Learn more about how to use this guide.

Found a bug? Report it!

Have a question about your account or billing? Reach out to our customer support team!

None of the above? Find out where to ask other questions here!

Hi,

I have a question on the exercise in the Linked List Review page.
It’s about the insert_beginning method, which looks like this when implemented as instructed:

  def insert_beginning(self, new_value):
    print("Function that takes a value parameter")
    new_node = Node(new_value)
    new_node.set_next_node(self.head_node)
    self.head_node = new_node

I wanted to add an alternative insert_beginning method that directly takes a Node as argument:

  def insert_beginning(self, new_node):
    print("Function that takes a Node parameter")
    new_node.set_next_node(self.head_node)
    self.head_node = new_node

To my knowledge, this is method overloading, but for some reason, this doesn’t work.

I tried the following test code:

a = Node(1)
b = Node(2)
d = Node(3)
llist = LinkedList(5)
llist.insert_beginning(d)
llist.insert_beginning(b)
llist.insert_beginning(2)
llist.insert_beginning(a)

which gives some pretty strange results because the code only seems to use the original value method.

Thanks for clearing this up! :slight_smile:

I myself am not very proficient in Python, and I only just completed this module.
But upon seeing your question, I tried your method.
It seems to work fine for me, it adds the node fine as a direct argument.

I’m thinking you could achieve what you want with modifying the original method instead, to accept Nodes as direct argument, with a “if isinstance(obj, class)” check
I made and tested the following:

def insert_beginning(self, new_value):
if isinstance(new_value, Node):
new_value.set_next_node(self.head_node)
self.head_node = new_value
else:
new_node = Node(new_value)
new_node.set_next_node(self.head_node)
self.head_node = new_node

This way it accepts both inputs. I hope this does not add to the confusion.

I completed the exercise “4. Linked List Implementation III,” but as I attempt the review exercises, I’m running into unexpected problems in my code.

As you can see, toward the bottom I define four nodes that are linked by definition.

I aim to use the LinkedList .stringify_list() method to create a string from the list of the values of the nodes.

The code doesn’t work as expected. The way my program runs, there is no next node beyond node1, whereas I want the program to keep on going to node2, then node3, then node4.

The output of print(linked.stringify_list()) is just a.

But given how I defined my nodes, I expect:

a
b
c
d

Please help!

class Node:
  def __init__(self, value, next_node=None):
    self.value = value
    self.next_node = next_node
    
  def get_value(self):
    return self.value
  
  def get_next_node(self):
    return self.next_node
  
  def set_next_node(self, next_node):
    self.next_node = next_node

class LinkedList:
  def __init__(self, value=None):
    self.head_node = Node(value)
  
  def get_head_node(self):
    return self.head_node
  
  def insert_beginning(self, new_value):
    new_node = Node(new_value)
    new_node.set_next_node(self.head_node)
    self.head_node = new_node
    
  def stringify_list(self):
    string_list = ""
    current_node = self.get_head_node()

# I believe this is where the problem lies. When the print() below is executed, it returns 'None'. The output I desire is node2. If (current_node.get_next_node() == None), then my string will not grow beyond "a".

    print(current_node.get_next_node())
    while current_node:
      if current_node.get_value() != None:
        string_list += str(current_node.get_value()) + "\n"
      current_node = current_node.get_next_node()
    return string_list
  
  def remove_node(self, value_to_remove):
    current_node = self.get_head_node()
    if current_node.get_value() == value_to_remove:
      self.head_node = current_node.get_next_node()
    else:
      while current_node:
        next_node = current_node.get_next_node()
        if next_node.get_value() == value_to_remove:
          current_node.set_next_node(next_node.get_next_node())
          current_node = None
        else:
          current_node = next_node
          
# Define four nodes to be linked using LinkedList methods.
node4 = Node("d")
node3 = Node("c", node4)
node2 = Node("b", node3)
node1 = Node("a", node2)

# Define a LinkedList with a head node with value "a"
linked = LinkedList("a") 

# ATTEMPT to print the string of the linked list. This attempt fails.
print(linked.stringify_list())

The problem is in the way the objects are added to the list. Although you instantiate the Node objects with both a value and a next_node attribute, when they are added to the class LinkedList, only the value attribute is retained.

def __init__(self, value=None):
    self.head_node = Node(value)

Therefore, only the last Node object added will remain. You must use the insert_beginning() method to add new nodes, as the Class is currently written. Then the code itself will take care of next_node.

1 Like

Thanks again. That makes sense to me.

I have another question, though this time I want to know if something I already have working could work even better.

Could my LinkedList method .remove_all() be leaner? Opening and closing two while loops seems slightly clunky to me.

I’m sharing my code for the exercise below.

class Node:
  def __init__(self, value, next_node=None):
    self.value = value
    self.next_node = next_node
    
  def get_value(self):
    return self.value
  
  def get_next_node(self):
    return self.next_node
  
  def set_next_node(self, next_node):
    self.next_node = next_node

class LinkedList:
  def __init__(self, value=None):
    self.head_node = Node(value)
  
  def get_head_node(self):
    return self.head_node
  
  def insert_beginning(self, new_value):
    new_node = Node(new_value)
    new_node.set_next_node(self.head_node)
    self.head_node = new_node
    
  def stringify_list(self):
    string_list = ""
    current_node = self.get_head_node()
    while current_node:
      if current_node.get_value() != None:
        string_list += str(current_node.get_value()) + "\n"
      current_node = current_node.get_next_node()
    return string_list
  
  def remove_node(self, value_to_remove):
    current_node = self.get_head_node()
    if current_node.get_value() == value_to_remove:
      self.head_node = current_node.get_next_node()
    else:
      while current_node:
        next_node = current_node.get_next_node()
        if next_node.get_value() == value_to_remove:
          current_node.set_next_node(next_node.get_next_node())
          current_node = None
        else:
          current_node = next_node

  def remove_all(self, value_to_remove):
    # First while loop: check if head node is to be removed.
    # If so, remove, and reset head node to next node.
    # Iterate until (self.head_node.get_value() != value_to_remove)
    head = self.get_head_node()
    while head:
      if head.get_value() == value_to_remove:
        self.head_node = head.get_next_node()
        head = self.head_node
      else:
        head = None
    # Now the computer knows the head node is not to be removed.
    # Second while loop: iterate through the nodes in the list.
    # If there is no next node:
    #   Return 'None' to close the loop.
    # Else, if the next node has the value to be removed: 
    #   Set the next node of the current node to be the NEXT
    #   next node rather than the next node. (Remove next node.)
    # Else:
    #   Move to the next node in the linked list and repeat.
    current_node = self.get_head_node()
    while current_node:
      next_node = current_node.get_next_node()
      if next_node == None:
        current_node = next_node
      elif next_node.get_value() == value_to_remove:
        current_node.set_next_node(next_node.get_next_node())
      else:
        current_node = next_node
  


ll = LinkedList(5)
ll.insert_beginning(90)
ll.insert_beginning(70)
ll.insert_beginning(70)
ll.insert_beginning(5675)
ll.insert_beginning(90)
ll.insert_beginning(5)
ll.insert_beginning(90)
ll.insert_beginning(90)

print(ll.stringify_list())

ll.remove_all(90)

# Print output after ll.remove_all(90)
print(ll.stringify_list())
1 Like

Modify remove_node() to return a certain value if it cycles through and never finds value_to_remove (a good idea anyway, to protect from a crash if a non-existent value is fed to it.)

Then in remove_all(), just call remove_node() repeatedly until that value is returned.

I really don’t understand what nodes are for. How can they be used in code. I see the “tree diagrams” online but I don’t understand how a programmer actually uses them for anything useful. How are these truly different than a few lists or dictionaries linked together?

They are list or dictionaries linked together! The “difference” is in the programming techniques you can use with them.
For instance, one of the projects in the course “Basic Graph Search Algorithms” provides a “map” of metro stations consisting of a dictionary keying each station to a list of its adjacent stations. There is also a dictionary of city landmarks keyed to nearest metro stations.
The completed project allows you to type in any two landmarks and get in return the shortest route between them.
You might be able to program that without using any tree-search techniques (monte-carlo simulations of many possible routes, perhaps), but I don’t think it would be as efficient.

How would you have remove_node() return a certain value if it doesn’t find value_to_remove?

        next_node = current_node.get_next_node()
        if not next_node:
          return "value not found"

[Check my “remove_all_specific_nodes” method ] :smiley:(https://gist.github.com/ad123a3910b2fc8b61c27fd1079d5ecb)

Edit1: I slightly modified the “stringify_list” method. Instead of it being a string, I decided to format it as a list, because it’s more convenient.

Edit2: I don’t know how to post my code like you guys… Could someone tell me how?