Blossom Project

I’m working on the blossom project under computer science, I noticed that under the LinkedList class which has a iter method that uses the (get_value()) method created in the Node class.
However when instantiating a LinkedList, there’s no such variable that is created using the Node class. Like at all.
So how can Node.get_value() be used to iterate the LinkedList instances?

class Node:
  def __init__(self, value):
    self.value = value
    self.next_node = None
    
  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, head_node=None):
    self.head_node = head_node
  
  def insert(self, new_node):
    current_node = self.head_node

    if not current_node:
      self.head_node = new_node

    while(current_node):
      next_node = current_node.get_next_node()
      if not next_node:
        current_node.set_next_node(new_node)
      current_node = next_node

  def __iter__(self):
    current_node = self.head_node
    while(current_node):
      yield current_node.get_value()
      current_node = current_node.get_next_node()

Also, why does the iter method not have next method to go with it too?

Hi,

When you instantiate a LinkedList here, you can specify its head_node or leave it to its default of None. When you specify its head_node, that will be of class Node, so it already has all the methods of the Node class.

The dunder method __iter__ just serves to explicitly deal with how the iteration should work out when a LinkedList object is iterated.

For reference, here’s a video on iterators: https://www.youtube.com/watch?v=jTYiNjvnHZY

1 Like

Thanks for the reply

Yeah I see where you’re coming from with the head_node, but nowhere in the constructor does it make the head_node an instance of a Node.

And I’ve seen that video, it’s got a next dunder too, so why doesn’t this one have it also?

The constructor doesn’t have to make it an instance of Node. That’s up to the user.

Example from the terminal:

>>> new_node = Node(5)
>>> new_node
<__main__.Node object at 0x7fca61327350>
>>> new_node.value
5
>>> new_linked_list = LinkedList(new_node)
>>> new_linked_list.head_node.value
5
>>> type(new_linked.head_node)
<class '__main__.Node'>

As to why they omit or include something in a video, I can’t speak to the video and its reasons. For basic functionality though, the code you quoted should do the job.

1 Like

I see my issue now.

Instantiating key-value of the flowers was done in the HashMap class instead of LinkedList class, thanks!

1 Like