Search code examples
pythonlinked-list

How to check if a Linked-List is empty in python?


I created a linked list that i want to check if it is empty, and if it is empty, it will return True, and if it is not empty, it will return False. I've tried a couple solutions for this. but this is one of the solutions i tried.

def isEmpty(self):
    current_node = self.head
    return current_node == None

But it seems to return False even when it is empty. BUt here is the whole code from the list so you can see how ive set it up

class Node:

    def __init__(self, data = None):
        self.data = data
        self.next = None

class LinkedList:

    def __init__(self):
        self.head = Node()

    def display(self):
        elements = []

        current_node = self.head
        while current_node.next != None:
            current_node = current_node.next
            elements.append(current_node.data)
        return elements

    def add(self, data):
        new_node = Node(data)
        current_node = self.head
        while current_node.next != None:
            current_node = current_node.next
        current_node.next = new_node

    def isEmpty(self):
        current_node = self.head
        return current_node == None

How would i fix this problem?


Solution

  • def isEmpty(self):
        return self.head.next is None