我试图在python中的数据结构链表之间添加元素,但我遇到了这个错误
我在这段代码中遇到了这个问题。我不知道如何修复类型错误。我已经做了几个小时了,我所做的每一个改变似乎都会带来更多的问题。我把这本书通读了一遍,却一无所获。我得到了一些东西,但这对我来说根本不起作用。我无情地搜索论坛。提前谢谢我在vs studio代码中使用python 3。
文件"d: \coding \python_in_hole\data structure\tempCodeRunnerFile.py",第69行,inroot.insert_at(2,31(文件";d: \coding \python_in_hole\data structure\tempCodeRunnerFile.py",第45行,插入_at如果索引<0或索引>self.get_length((:类型错误:">"在"int"one_answers"NoneType"的实例之间不支持
class Node:
def __init__(self, data=None, next=None):
self.data = data
self.next = next
class linked_list:
def __init__(self):
self.head = None
def insert_at_begining(self, data):
node = Node(data, self.head)
self.head = node
def print(self):
itr = self.head
llstr = ''
while itr:
suffix = ''
if itr.next:
suffix = '-->'
llstr += str(itr.data) + suffix
itr = itr.next
print(llstr)
def get_length(self):
count = 0
itr = self.head
while itr:
count = count+1
itr = itr.next
print(count)
def insert_at_end(self, data):
if self.head is None:
self.head = Node(data, None)
return
itr = self.head
while itr.next:
itr = itr.next
itr.next = Node(data, None)
def insert_at(self, index, data):
if index < 0 or index > self.get_length():
raise Exception("Invalid Index")
if index == 0:
self.insert_at_begining(data)
return
itr = self.head
count = 0
while itr:
if count == index-1:
node = Node(data, itr.next)
itr.next = node
break
itr = itr.next
count += 1
if __name__ == '__main__':
root = linked_list()
root.insert_at_begining(5)
root.insert_at_begining(15)
root.insert_at_begining(10)
root.insert_at_end(34)
root.insert_at(2, 31)
root.insert_at_end(45)
root.print()
root.get_length()
您在get_length
方法中错过了一个返回语句。所以你的代码看起来像这个
class Node:
def __init__(self, data=None, next=None):
self.data = data
self.next = next
class linked_list:
def __init__(self):
self.head = None
def insert_at_begining(self, data):
node = Node(data, self.head)
self.head = node
def print(self):
itr = self.head
llstr = ''
while itr:
suffix = ''
if itr.next:
suffix = '-->'
llstr += str(itr.data) + suffix
itr = itr.next
print(llstr)
def get_length(self):
count = 0
itr = self.head
while itr:
count = count+1
itr = itr.next
print(count)
return count
def insert_at_end(self, data):
if self.head is None:
self.head = Node(data, None)
return
itr = self.head
while itr.next:
itr = itr.next
itr.next = Node(data, None)
def insert_at(self, index, data):
if index < 0 or index > self.get_length():
raise Exception("Invalid Index")
if index == 0:
self.insert_at_begining(data)
return
itr = self.head
count = 0
while itr:
if count == index-1:
node = Node(data, itr.next)
itr.next = node
break
itr = itr.next
count += 1
if __name__ == '__main__':
root = linked_list()
root.insert_at_begining(5)
root.insert_at_begining(15)
root.insert_at_begining(10)
root.insert_at_end(34)
root.insert_at(2, 31)
root.insert_at_end(45)
root.print()
root.get_length()
输出将像这个
4
10-->15-->31-->5-->34-->45
6