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 1obj1 = SinglyLinkedList()obj1.insertHead(8)obj1.insertHead(7)obj1.insertHead(5)obj1.insertTail(30)print(obj1.displayNodes())### Object 2obj2 = SinglyLinkedList()obj2.insertHead(20)obj2.insertHead(10)print(obj2.displayNodes())### Object 3obj3 = SinglyLinkedList()obj3.insertHead(50)obj3.insertHead(22)obj3.insertHead(19)print(obj3.displayNodes())print(obj3.nodes)### Object 4obj4 = 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”的列表变量中。对于每个实例,我都返回该列表变量“节点”。如您所见,从第二个实例的输出来看,前一个实例的节点显示仍保持原样。我想知道为什么会这样,因为对于每个实例,存储都是单独分配给该实例的。
1 回答
四季花海
TA贡献1811条经验 获得超5个赞
因为nodes
是(本质上)一个静态变量。
您可能打算这样写:
class SinglyLinkedList: def __init__(self): self.nodes = [] self.head = None self.tail = None
添加回答
举报
0/150
提交
取消