简体   繁体   English

在Python中实现链接列表很麻烦

[英]Trouble with implementing a linked list in Python

There's this HackerRank problem about implementing a linked list. 存在有关实现链接列表的HackerRank问题。 It is pretty basic and I thought I'd do it in a jiffy since I'd done all kinds of linked list implementations in C++. 这是非常基本的,我想我会做一点,因为我已经用C ++完成了各种链表实现。 But I'm stuck somewhere. 但是我被困在某个地方。

class Node:
    def __init__(self,data):
        self.data = data
        self.next = None
class Solution:
    def display(self,head):
        current = head
        while current:
            print current.data,
            current = current.next  

    def insert(self,head,data): 
        new_node = Node(data)
        if head == None:
            head = new_node
        else:
            current = head
            while current.next:
                current = current.next
            current.next = new_node

mylist= Solution()
T=int(input())
head=None
for i in range(T):
    data=int(input())
    head=mylist.insert(head,data)   
mylist.display(head)

Only the insert function is editable. insert功能是可编辑的。 The rest of the code is provided by HackerRank and cannot be changed. 其余代码由HackerRank提供,无法更改。 The code doesn't print anything at the end of the insertions, and when I tried to print out the values while inserting, it seemed like the head kept on moving forwards instead of staying at the beginning. 该代码在插入的末尾不显示任何内容,当我尝试在插入时打印出这些值时,看起来head始终向前移动而不是停留在开始位置。

You are appending the new_node after all the elements, and also you are not returning the newly created node. new_node附加在所有元素之后,并且也不会返回新创建的节点。 Modify your insert method like this: 像这样修改您的insert方法:

def insert(self,head,data): 
    new_node = Node(data)
    if head is not None:
        current = head
        new_node.next = current
    return new_node

I think the error is here: 我认为错误在这里:

head = mylist.insert(head, data)

the method Solution.insert() is not returning anything, therefore head is assigned None every time. 该方法Solution.insert()不返回任何内容,因此每次都将head分配为None。

When done, Solution.insert() must return the new_node created 完成后, Solution.insert()必须返回创建的new_node

The reason your code doesn't work is because of the None check that you are doing in insert method. 您的代码不起作用的原因是因为您在insert方法中正在执行None检查。

if head == None:
        head = new_node

The head you are updating is local to the function insert and doesn't change head in the loop. 您要更新的head位于函数insert本地,并且不会在循环中更改head So, head is always None in your loop. 因此, head在循环中始终为None

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM