1
class Node:
    def __init__(self, value):
        self.data = value
        self.next = None
        
class SinglyLinkedList:
    nodes = []
    
    def __init__(self):
        self.head = None
        self.tail = None
    
    def insertHead(self, value):
        node = Node(value)
        
        if(self.head is None):
            self.head = node
            self.tail = node
            return
        
        node.next = self.head
        self.head = node
        
    def insertTail(self, value):
        node = Node(value)
        
        if(self.tail is None):
            self.head = node
            self.tail = node
            return
        
        self.tail.next = node
        self.tail = node
    
    def displayNodes(self):
        temp = self.head
        
        while (temp is not None):
            self.nodes.append(temp.data)
            temp = temp.next
            
        return self.nodes    
        
### Object 1
obj1 = SinglyLinkedList()
obj1.insertHead(8)
obj1.insertHead(7)
obj1.insertHead(5)
obj1.insertTail(30)
print(obj1.displayNodes())

### Object 2
obj2 = SinglyLinkedList()
obj2.insertHead(20)
obj2.insertHead(10)
print(obj2.displayNodes())

### Object 3
obj3 = SinglyLinkedList()
obj3.insertHead(50)
obj3.insertHead(22)
obj3.insertHead(19)
print(obj3.displayNodes())
print(obj3.nodes)

### Object 4
obj4 = SinglyLinkedList()
obj4.insertHead(45)
obj4.insertHead(40)
obj4.insertHead(35)
obj4.insertHead(28)
print(obj4.displayNodes())

输出

python flatten_LL.py
[5, 7, 8, 30]
[5, 7, 8, 30, 10, 20]
[5, 7, 8, 30, 10, 20, 19, 22, 50]
[5, 7, 8, 30, 10, 20, 19, 22, 50]
[5, 7, 8, 30, 10, 20, 19, 22, 50, 28, 35, 40, 45]

这是一个单链表的代码。我创建了四个实例,并将链表值存储在名为“nodes”的列表变量中。对于每个实例,我都返回该列表变量“节点”。正如您所看到的输出,从第二个实例开始,节点的显示前一个实例的输出仍然保持原样。我想知道为什么会发生这种情况,因为对于每个实例,存储都是单独分配给该实例的。

4

1 回答 1

2

因为nodes(本质上)是一个静态变量

你可能打算这样写:

class SinglyLinkedList:    
    def __init__(self):
        self.nodes = []
        self.head = None
        self.tail = None
于 2020-08-10T14:52:30.107 回答