class Node:
def __init__(self,data):
self.data=data
self.next=None
head=Node(10)
head.next=Node(20)
head.next.next=Node(30)
head.next.next.next=Node(40)
head.next.next.next.next=Node(50)
def insertAtBegnning(head,x):
temp=Node(100)
temp.next=head
return temp
head =insertAtBegnning(head,90)
1.在上面的函数中,我可以在开始时添加新节点,但我用了另一种方式,因为在链接列表的开头,我无法添加新节点。
def insertAtBegning(head,x):
temp=head
head=Node(x)
head.next=temp
return head
insertAtBegning(head,100)
def displayLinkedList(head):
curr=head
while(curr!=None):
print (curr.data)
curr=curr.next
displayLinkedList(head)
结果:我得到10,20,30,40,50,但我应该得到100,10,10,20,30,40,50
2.有人能告诉我我在上面的函数哪里出错了吗?
发布于 2021-01-11 05:36:36
当您返回head
时,需要更新它的值:
def insertAtBegning(head,x):
temp=head
head=Node(x)
head.next=temp
return head
# update 'head' here
head = insertAtBegning(head,100)
def displayLinkedList(head):
curr=head
while(curr!=None):
print (curr.data)
curr=curr.next
displayLinkedList(head)
https://stackoverflow.com/questions/65496314
复制相似问题