python - Insert new element as the head of the Linkedlist Python
问题描述
I want to add an element at the beginning of a Linkedlist, but None
is added instead of the actual element
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
解决方案
Your insert
method seems fine. The problems seems to be that you initialize self.head
as an empty Node()
but never update that node's data
. Adding a repr
method to Node
as
def __repr__(self):
return "(%r, %r)" % (self.data, self.next)
we see that after appending or inserting the numbers from range(10)
, the result looks like this:
(None, (0, (1, (2, (3, (4, (5, (6, (7, (8, (9, None)))))))))))
(9, (8, (7, (6, (5, (4, (3, (2, (1, (0, (None, None)))))))))))
Instead, you should initialize self.head
as None
and add an accordant check to 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)
Then, the result looks like this:
(0, (1, (2, (3, (4, (5, (6, (7, (8, (9, None))))))))))
(9, (8, (7, (6, (5, (4, (3, (2, (1, (0, None))))))))))
You also have to adapt your display
method as it skips the first element in the list, which is probably why you did not notice the bug for 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)
推荐阅读
- node.js - 为什么 Babel 不转译我的 React 应用程序导入?
- php - Cakephp 3.6:两个表之间的多个外键
- php - Laravel:如何将值 api 数据传递给查看文件
- mysql - 为什么MySQL事务锁只阻塞其他锁?
- spring-mvc - hibernate spring mvc +jsp中的一对多映射
- java - HttpServletRequest 字段可能不是静态的、最终的或与球衣 2 有注释类型错误
- ajax - Angular HttpClient 流
- assembly - 在执行到达另一个带有 RET 的函数之前,PUSHing 地址会做什么?
- javascript - 如何获得上一个/下一个 | 使用 list.js 分页的第一个/最后一个按钮
- java - 如何在 Spark 结构化流中读取 orc 数据源?