Build a Linked List - Step 11

Tell us what’s happening:

class LinkedList:
class Node:
def init(self, element):
self.element = element
self.next = None

def __init__(self):
    self.length = 0
    self.head = None

def is_empty(self):
    return self.length == 0

def add(self, element):
    node = self.Node(element)
    if self.is_empty():
        self.head = node
    else:
        current_node = self.head   # <-- assign self.head to current_node

Your code so far

class LinkedList:
    class Node:
        def __init__(self, element):
            self.element = element
            self.next = None
            
    def __init__(self):
        self.length = 0
        self.head = None

    def is_empty(self):
        return self.length == 0
    

# User Editable Region

    def add(self, element):
        node = self.Node(element)
        if self.is_empty():
            self.head = node
        else:
            current_node = self.head   # <-- assign self.head to current_node

            while current_node.next is not None:
                current_node = current_node.next

            current_node.next = node

# User Editable Region

        self.length += 1

    def print_list(self):
        cur = self.head
        while cur:
            print(cur.element, end=" -> " if cur.next else "\n")
            cur = cur.next


# Test
my_list = LinkedList()
print(my_list.is_empty())  # True
my_list.add(1)
my_list.add(2)
my_list.add(3)
print(my_list.is_empty())  # False
my_list.print_list()       # 1 -> 2 -> 3

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/144.0.0.0 Safari/537.36

Challenge Information:

Build a Linked List - Step 11

Please Tell us what’s happening in your own words.

Learning to describe problems is hard, but it is an important part of learning how to code.

Also, the more you say, the more we can help!