我是 python 的初学者,现在我在这个程序中遇到了问题。
首先是 NodeList:<-linklist
class Node:
def __init__(self,initdata):
self.data = initdata
self.next = None
def getData(self):
return self.data
def getNext(self):
return self.next
def setData(self,newdata):
self.data = newdata
def setNext(self,newnext):
self.next = newnext
这是我的程序:
from NodeList import Node
class DequeLL:
def __init__(self):
self.head = None
self.last = None
self.length = 0
def addFrontDLL(self, item):
temp = Node(str(item))
temp.setNext(self.head)
self.head = temp
length = max(len(node.data) for node in self.allNodes()) if self.head else 0
print('\u2510{}\u250c'.format(' '*length))
for node in self.allNodes():
print('\u2502{:<{}}\u2502'.format(node.data, length))
print('\u2514{}\u2518'.format('\u2500'*length))
def addRearDLL(self, item):
node = Node(str(item))
node.next = None
if self.length == 0:
self.head = self.last = node
else:
last = self.last
last.next = node
self.last = node
self.length = self.length + 1
length = max(len(node.data) for node in self.allNodes()) if self.head else 0
print('\u2510{}\u250c'.format(' '*length))
for node in self.allNodes():
print('\u2502{:<{}}\u2502'.format(node.data, length))
print('\u2514{}\u2518'.format('\u2500'*length))
def allNodes(self):
node = self.head
while node is not None:
yield node
node = node.next
d = DequeLL()
当我在 addFrontDLL 中添加一个项目时,一切都很好。但是在 addRearDLL 中添加一个项目后,它就像该项目被添加到另一个容器中一样。然后我尝试再次使用 addFrontDLL 添加它,它按我想要的方式工作(该项目被添加到另一个容器上)。见下图:
我希望有人为我解释并修复它。任何帮助将不胜感激。谢谢你。