在Python3链接列表的开头插入一个项目



如何修改以下代码?以便使用add((将该项插入到链表的开头?为什么"无"显示在链接列表的开头?有什么问题吗?我试了好几次。它就是不起作用。他做了什么?有什么改变的建议吗?在写链表时有什么好的建议吗?

class Node:
def __init__(self, data=None):
self.data= data
self.next = None
class linkedlist:
def __init__(self):
self.head=Node()

def append(self,data):
cur_node = self.head
new_node=Node(data)
while cur_node.next != None:
cur_node = cur_node.next
cur_node.next=new_node

def display(self):
lst=[]
cur_node=self.head
while cur_node.next!=None:
cur_node = cur_node.next
lst.append(cur_node.data)
return lst
def length(self):
cur_node=self.head
c=0
while cur_node.next!=None:
cur_node = cur_node.next
c+=1
return c
def get(self,index):
if index >=self.length():
print('out of bond!')
return None
cur_index=0
cur_node=self.head
while True:
cur_node=cur_node.next
if cur_index==index: return cur_node.data
cur_index+=1

def erase(self,index):
if index>=self.length():
print('out of bound')
return None
cur_index=0
cur_node=self.head

while True:
temp=cur_node
cur_node=cur_node.next
if cur_index==index:

temp.next=cur_node.next
print('erase',index)
return
cur_index+=1
def add(self,data):
cur_node=Node(data)
cur_node.next=self.head
self.head=cur_node

LL=linkedlist()
LL.append(1)
LL.append(2)
LL.append(3)
LL.append(4)
print(LL.add(999))
print(LL.display())
None
[None, 1, 2, 3, 4]

为什么没有999以及如何从一开始就删除None?

由于链表是用一个伪节点head创建的,所有其他方法都依赖于这个假设,add永远不应该取代它。这个伪节点背后的想法是,它永远都在那里,永远不会改变。它有助于保持代码的简单性(以一个额外节点的内存为代价(。

因此,避免add更改head属性。新节点应插入在head:之后

def add(self,data):
cur_node=Node(data)
cur_node.next=self.head.next
self.head.next=cur_node

最新更新