python - 为什么此链接列表代码在 HackerRank 中显示错误?

标签 python data-structures linked-list

我已经在 IDLE 中使用此代码实现了链表。如果我遍历它会显示预期的输出。但在黑客圈子里我遇到了麻烦。我缺少什么? 这是问题link

class Node:
    def __init__(self,data=None,next_node = None):
        self.data = data
        self.next_node = next_node

    def get_data(self):
        return self.data
    def get_next(self):
        return self.next_node
    def set_next(self,new_next):
        self.next_node = new_next
class LL:
    def __init__(self,head=None,tail=None):
       self.head = head   #head
       self.tail = tail   #tail
    def Insert(self,data):
        new_node =  Node(data) #new_node
        new_node.set_next(None)

        if self.head == None:

            self.head = new_node
            self.tail = new_node
        else:
            self.tail.set_next(new_node)
            self.tail = new_node

最佳答案

Python 中的 getter 和 setter 是多余的。另外,你把事情搞得太复杂了。

只有两种情况您需要担心;一般情况,以及 headNone 时的极端情况。

解决方案1
迭代

def Insert(head, data):
    # handle the corner case
    if not head:
        return Node(data)

    # handle the general case
    temp = head
    while temp.next:
        temp = temp.next
    temp.next = Node(data)

    return head
<小时/>

解决方案2
递归

def Insert(head, data):
    if not head:
        return Node(data)

    head.next = Insert(head.next, data)
    return head

这两种解决方案都通过了 Hackerrank 上的所有测试用例。

关于python - 为什么此链接列表代码在 HackerRank 中显示错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48405442/

相关文章:

python - 如何使用cv2.min封闭圆显示物体检测线

algorithm - 二叉搜索树中的底层实现

c++ - 如何将 head 从 main 传递到 addNode 函数? (通过结构实现 LinkedList)

java - LinkedList 为同一功能提供了多种方法-为什么?

c++ - 代码不编译 - 链表,按升序排序列表

python - 如何在peewee中选择虚拟列?

python - 尝试在 Docker 中将 TkInter 与 Socat 一起使用 - Mac

python - 如何使用预训练的keras模型作为模型add函数的参数?

java - 为什么在 Java 中更喜欢使用列表而不是数组?

java - 对于以下用例,什么可以更快地实现 trie?