简体   繁体   English

如何检查python中的链表是否为空?

[英]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 .我创建了一个链表,我想检查它是否为空,如果为空,则返回True ,如果不为空,则返回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.但即使它是空的,它似乎也返回 False 。 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?我将如何解决这个问题?

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM