大家好,我正在制作链接列表,但出现此错误
Traceback (most recent call last):
File "python", line 144, in <module>
File "python", line 93, in get
AttributeError: 'NoneType' object has no attribute 'next'
这是否意味着我不使用next,或者可能是这里完全缺少的东西?还是我没有正确构建链接列表?
class Node(object):
def __init__(self,data):
self.data = data
self.next = None
class MyLinkedList(object):
def __init__(self):
"""
Initialize your data structure here.
"""
self.head = None
self.size = 0
def get(self, index):
"""
Get the value of the index-th node in the linked list. If the
index is invalid, return -1.
:type index: int
:rtype: int
"""
if index <= 0 or index > self.size: #checks if index is less the 0 and chech if the index requested is bigger #then
return -1 #self.size
else:
current = self.head
for i in range(self.size):
if i != index:
current = current.next
else:
return current.data
def addAtHead(self, val):
"""
Add a node of value val before the first element of the linked
list. After the insertion, the new node will be the first node of the
linked list.
:type val: int
:rtype: void
"""
current = self.head
node = Node(val)
if current is None:
current = node
else:
current.next = self.head
self.head = node
self.size = self.size + 1
def addAtTail(self, val):
"""
Append a node of value val to the last element of the linked list.
:type val: int
:rtype: void
"""
tail = Node(val)
if self.head is None:
self.head = tail
else:
tmp = self.head
while tmp is not None:
tmp.next
tmp = tail