我想在链接列表的开头添加一个元素,但是添加了None
而不是实际元素
class Node:
#initialize the head node to none if not provided and set the next node to none
def __init__(self,data=None):
self.data = data
self.next = None
class Linkedlist:
def __init__(self):
self.head = Node()
def append(self,data):
#creating the node with the data parameter
new_node = Node(data)
current_node = self.head
while current_node.next is not None:
current_node = current_node.next
#when we have reached the end of list
current_node.next = new_node
def display(self):
#container for the nodes
node_elements = []
current_node = self.head
while current_node.next is not None:
current_node = current_node.next
node_elements.append(current_node.data)
print(node_elements)
#Here is where there is the issue
def insert_as_first_element(self,data):
new_node = Node(data)
new_node.next = self.head
self.head = new_node
答案 0 :(得分:1)
您的insert
方法似乎不错。问题似乎在于您将self.head
初始化为空的Node()
,但从未更新该节点的data
。向repr
添加Node
方法为
def __repr__(self):
return "(%r, %r)" % (self.data, self.next)
我们看到,在range(10)
中添加或插入数字后,结果如下:
(None, (0, (1, (2, (3, (4, (5, (6, (7, (8, (9, None)))))))))))
(9, (8, (7, (6, (5, (4, (3, (2, (1, (0, (None, None)))))))))))
相反,您应该将self.head
初始化为None
并向append
添加一致的检查:
def __init__(self):
self.head = None
def append(self,data):
if self.head is None:
self.head = Node(data)
else:
cur = self.head
while cur.next is not None:
cur = cur.next
cur.next = Node(data)
然后,结果看起来像这样:
(0, (1, (2, (3, (4, (5, (6, (7, (8, (9, None))))))))))
(9, (8, (7, (6, (5, (4, (3, (2, (1, (0, None))))))))))
您还必须调整display
方法,因为它会跳过列表中的第一个元素,这可能就是为什么您没有注意到append
的错误的原因。
def display(self):
node_elements = []
cur = self.head
while cur is not None:
node_elements.append(cur.data)
cur = cur.next
print(node_elements)
答案 1 :(得分:0)
问题出在您的display
函数中,您需要在其中切换提取数据并继续到下一个节点的顺序。否则,您将不会打入您在列表中输入的第一个节点。
while current_node.next is not None: node_elements.append(current_node.data) current_node = current_node.next
答案 2 :(得分:0)
您的问题并不在于插入本身,它开始得早于None
底部的空(LinkedList
)节点。然后,当您在列表的开头插入一个元素时,该节点将被推入结构,使其出现在您的display()
调用中(假设current_node.next
现在是空节点)。
如果要在链接列表的根目录中保留一个空节点,一个简单的解决方法是将其保留在那里并对其子节点进行操作:
def insert_as_first_element(self, data):
new_node = Node(data)
new_node.next = self.head.next
self.head.next = new_node