所以我一直试图在链表的前面插入一个项目,它有点工作,但不完全。这是我到目前为止所拥有的(LinkedList 类中有更多方法,但我省略了它们,因为它们不是问题):
class _Node():
def __init__(self, data=None, link=None):
self.data = data
self.link = link
class LinkedList():
def __init__(self):
self.first = None
self.size = 0
def insert(self, ind, item):
if self.first is None:
self.first = _Node(item)
elif ind == 0: # this is where the problem is. When I try to
temp = self.first # insert a node to the front, it seems to
temp.link = self.first.link # forget about the rest of the nodes.
self.first = _Node(item)
self.first.link = temp
else:
count = 0
while count != ind - 1:
count += 1
self.first = self.first.link
self.first.link = _Node(item, self.first.link)
self.size += 1
说我在shell中有这个:
>>> L = LinkedList()
>>> L.insert(0, 5)
>>> L.insert(1, 10)
>>> L.insert(0, 20)
>>> L[0]
20
>>> L[1]
5
>>> L[2]
# and here is an error message, it says NoneType object has no attribute 'data'
所以在我上面的代码中,我要做的是创建一个与第一个节点对象相同的临时节点对象,我将该临时节点链接到第一个节点链接,我创建新节点,然后链接那个新节点节点到临时节点,但这不起作用。任何帮助都会很棒,谢谢!