我正在努力实现linked list
来研究数据结构。互联网上有很多很好的资源,但我仍然不明白我的代码的哪一部分不起作用。
class Node:
def __init__(self, val=None):
self.data = val
self.Next = None
class LinkedList:
def __init__(self):
self.head = None
self.size = 0
def __repr__(self):
temp = self.head
alist = []
while temp.Next is not None:
alist.append(temp.data)
temp = temp.Next
return str(alist)
def add(self, val):
cur = self.head
prev = None
if cur is None:
self.head = Node(val)
else:
while cur is not None:
prev = cur
cur = cur.Next
prev.Next = Node(val)
self.size += 1
if __name__ == '__main__':
alist = LinkedList()
for i in range(10):
alist.add(i)
print(alist)
""" [0,1,2,3,4,5,6,7,8]
我希望它打印出 [0,1,2,3,4,5,6,7,8,9],但它错过了最后一个元素。谁能告诉我我在add
方法上错过了什么? 提前感谢!
需要明确的是,我最初的add
方法是这样的,
def add(self, val):
temp = Node(val)
temp.Next = self.head
self.head = temp
self.size += 1
但是,它会以相反的顺序添加元素,例如 [9,8,7,6,5,4,3,2,1,0]。所以我把add
改成了
def add(self, val):
cur = self.head
prev = None
if cur is None:
self.head = Node(val)
else:
while cur is not None:
prev = cur
cur = cur.Next
prev.Next = Node(val)
self.size += 1
我以前打印出链表内的所有元素都没有问题,但是新方法不会打印出最后一个元素。这是我__repr__
问题,而不是add
.我换了__repr__
.谢谢@inspectorG4dget