所以我已经解决了几个问题,通过在这里和我认识的人那里获得帮助。我的问题的根源是我不知道如何包装 None 以便我不会不断收到这些没有属性或不可调用的错误。
对于这个链表,我真正需要的是插入和打印列表。我没有包括打印列表,因为它很简单,并且不会引起问题。
错误位于 Linked_List 下、插入下、elif 下。它是这样评论的:#<----ERROR
这是代码:
class Node:
def __init__(self, word):
self.data = word
self.next = None
def nextNode(self):
if self.next is not None:
return self.next
else:
return None
def getData(self):
return self.data
def setNext(self, node):
self.next = node
def hasNext(self):
if self.next == None:
return False
else:
return True
class Linked_List:
def __init__(self):
self.head = Node(None)
self.isempty = True
def insert(self, word):
newNode = Node(word)
prev = self.head.nextNode()
current = self.head.nextNode()
nextFound = False #the next would be the current when it is less than node
#Look for position to insert:
#When empty
if self.isempty == True:
self.isempty = False
self.head = newNode
#When has more than one
elif self.head.hasNext():
while nextFound == False:
if current.getData() > newNode.getData():
prev = current
current = curent.nextNode()
else:
nextFound = True
#Insert
prev.next().setNext(newNode) # <-------ERROR -----HERE~~
newNode.setNext(current)
else:
#When only has one node not empty
if self.head.getData() > newNode.getData():
self.head.setNext(newNode)
else:
newNode.setNext(self.head)
self.head = newNode
插入:
lList.insert(string)
在这里解决:
class Linked_List:
def __init__(self):
self.head = Node(None)
self.isempty = True
def insert(self, word):
newNode = Node(word)
prev = self.head.nextNode()
current = self.head.nextNode()
nextFound = False #the next would be the current when it is less than node
#Look for position to insert:
#When empty
if self.isempty == True:
self.isempty = False
self.head = newNode
#When has more than one
elif self.head.hasNext():
while nextFound == False and current != None:
if current.getData() > newNode.getData():
prev = current
if current.hasNext():
current = current.nextNode()
else:
current = None
else:
nextFound = True
#Insert
prev.setNext(newNode)
newNode.setNext(current)
else:
#When only has one node not empty
if self.head.getData() > newNode.getData():
self.head.setNext(newNode)
else:
newNode.setNext(self.head)
self.head = newNode