我为一个UnorderedList()类创建了一个append方法,该类在我的IDLE窗口中正常工作,但当它被分配到大学的测试时:
my_list = UnorderedList()
my_list.append(13)
for num in my_list:
print(num, end=" ")
print()
它会返回错误:AttributeError: Nonetype object has no attribute 'getNext'
。
这是追加方法:
def append(self,item):
current = self.head
while current.getNext() != None:
current = current.getNext()
current.setNext(Node(item))
以下是我的其他课程和代码:
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
class UnorderedList:
def __init__(self):
self.head = None
self.count = 0
def append(self,item):
current = self.head
while current.getNext() != None:
current = current.getNext()
current.setNext(Node(item))
为什么测试会返回该错误以及如何修复我的追加方法?
答案 0 :(得分:7)
问题在于附加方法:
def append(self,item):
current = self.head
while current.getNext() != None:
current = current.getNext()
current.setNext(Node(item))
在第一次迭代中,current
的值为self.head
,最初设置为None
,您不会检查它。
相反,改变这一点并在下面引入对此条件的检查:
def append(self,item):
current = self.head
if current:
while current.getNext() != None:
current = current.getNext()
current.setNext(Node(item))
else:
self.head = Node(item)
PS:您还使用了一个变量self.count
,您没有更新。您可能也希望同样更新它。
答案 1 :(得分:1)
你的append方法工作正常,但它遍历列表,直到找到最后一个节点 - 这使得它成为O(n)。如果跟踪最后一个节点,可以进行附加,即O(1):
> (if true 0) ; test-expr = true, then-expr = 0
if: missing an "else" expression in: (if true 0)
> (if true 0 1) ; test-expr = true, then-expr = 0, else-expr = 1
0
> (if false 0 1) ; test-expr = false, then-expr = 0, else-expr = 1
1
要启用此功能,列表类构造函数应为:
def append_O1(self, item):
temp = Node(item)
last = self.tail
last.setnext(temp)
self.tail = temp
self.length += 1
答案 2 :(得分:1)
添加更多精心设计的追加方法
在开头插入的方法
def inserAtBeginning(self, item):
newNode = Node(item)
newNode.setdata(item)
if self.listLength() == 0:
self.head = newNode
else:
newNode.setnext(self.head)
self.head = newNode
最后插入的方法
def insertAtEnd(self, item):
newNode = Node(item)
newNode.setdata(item)
current = self.head
while current.getnext() != None:
current = current.getnext()
current.setnext(newNode)
在指定位置插入的方法
def insertAtPos(self, pos, item):
if pos > self.listLength() or pos < 0:
return None
if pos == 0:
self.inserAtBeginning(item)
else:
if pos == self.listLength():
self.insertAtEnd(item)
else:
newNode = Node(item)
newNode.setdata(item)
current = self.head
count = 0
while count < pos - 1:
count += 1
current = current.getnext()
newNode.setnext(current.getnext())
current.setnext(newNode)
答案 3 :(得分:1)
此O(n)实现也应适用于空列表:
def append(self,item):
current = self.head
if current == None:
self.head = Node(item)
else:
while current.getNext() != None:
current = current.getNext()
current.setNext(Node(item))