有关双向链接列表中的Self.Head的问题

时间:2019-12-06 01:53:58

标签: python linked-list

我正在学习双向链接列表,并获得了以下代码,可以将项目推入双向链接列表并从列表中打印项目

class Node():
    def __init__(self,data):
        self.data = data
        self.prev = None
        self.next = None
class DoublyLinkedList:
    def __init__(self):
        self.head = None
    def push(self,data):
        newNode = Node(data)
        newNode.next = self.head
        if not self.head:
            **self.head.prev = newNode**
        self.head = newNode
    def printList(self):
        temp = self.head
        while temp:
            print(temp.data)
            temp = temp.next
ld = DoublyLinkedList()
ld.push(2)

它抛出一个关于“ self.head.prev = newNode”的错误,说“'NoneType'对象没有属性'prev'”,但是,如果我将“ if not self.head:”定义为“ if self.head不是“ None:”,如下:

class Node():
    def __init__(self,data):
        self.data = data
        self.prev = None
        self.next = None
class DoublyLinkedList:
    def __init__(self):
        self.head = None
    def push(self,data):
        newNode = Node(data)
        newNode.next = self.head
        **if self.head is not None:**
            self.head.prev = newNode
        self.head = newNode
    def printList(self):
        temp = self.head
        while temp:
            print(temp.data)
            temp = temp.next
ld = DoublyLinkedList()
ld.push(2)
ld.printList()

任何人都可以就“如果不是self.head:”和“如果self.head不为None:”之间的区别给出一些建议吗?

0 个答案:

没有答案