简体   繁体   English

检查链表是否为空

[英]Check whether a linked list is empty or not

Here is my code.这是我的代码。 I created a linked list manually to check if my method works or not.我手动创建了一个链表来检查我的方法是否有效。 But the output I get is nothing.但是我得到的 output 什么都不是。 There is no output没有output

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

node1=Node(2)
node2=Node(4)
node3=Node(5)
node1.next=node2
node2.next=node3
a=node1

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

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

hello=MyList()
print(hello.isEmpty(a))


In case you want to add data to LinkedList, you need to set the head of the list manually.如果要将数据添加到 LinkedList,则需要手动设置列表的头部。 This code is probably what you want:这段代码可能是你想要的:

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

node1=Node(2)
node2=Node(4)
node3=Node(5)
node1.next=node2
node2.next=node3

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

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

hello=MyList()
print(hello.isEmpty())


new_hello = MyList()
new_hello.head=node1
print(new_hello.isEmpty())

Output Output

True
False

You never set the head node to point to another node in the way you're currently doing it (your head and "a" aren't actually the same node here).您永远不会以当前的方式将头节点设置为指向另一个节点(您的头和“a”实际上不是同一个节点)。 Pass in another variable as a node object to change this.传入另一个变量作为节点 object 来更改它。

a = node1
class MyList():
    def __init__(self, head):
        self.head = head

    def isEmpty(self):
        return self.head is None # a linked list with a head is technically not empty

new_hello = MyList(a)
print (new_hello.isEmpty())

personally I would add an add_node(self, value) method and keep track of the end node as well, instead of doing it the way you are我个人会添加一个add_node(self, value)方法并跟踪结束节点,而不是按照你的方式做

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

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