首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
社区首页 >问答首页 >在链接列表的开头插入

在链接列表的开头插入
EN

Stack Overflow用户
提问于 2020-12-29 17:35:46
回答 1查看 33关注 0票数 0
代码语言:javascript
运行
复制
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.在上面的函数中,我可以在开始时添加新节点,但我用了另一种方式,因为在链接列表的开头,我无法添加新节点。

代码语言:javascript
运行
复制
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.有人能告诉我我在上面的函数哪里出错了吗?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-01-11 13:36:36

当您返回head时,需要更新它的值:

代码语言:javascript
运行
复制
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)
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/65496314

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档