在链表的尾部插入一个节点 python HackerRank

Oja*_*ale 1 python linked-list

它是一个在链表末尾添加节点的非常简单的程序。我不知道我在做什么错误。是否与hackerRank 的exoected 输出有关,或者我的代码中有错误。我正在尝试实现 Python2

class Node(object):

   def __init__(self, data=None, next_node=None):
       self.data = data
       self.next = next_node
def Insert(head, data):

    if (head.head == None):
        head.head = Node(data)
    else:
        current = head.head
        while (current.next != None) and (current.data == data):
                           current = current.next
        current.next = Node(data)
Run Code Online (Sandbox Code Playgroud)

这是问题的链接。 https://www.hackerrank.com/challenges/insert-a-node-at-the-tail-of-a-linked-list

Alo*_*kur 6

如果您必须在链接列表的末尾添加,则不需要测试current.data == data,下面的代码应该足够了-

def Insert(head, data):

    if (head == None):
        head = Node(data)
    else:
        current = head
        while (current.next != None):
            current = current.next
        current.next = Node(data)
    return head
Run Code Online (Sandbox Code Playgroud)

另请注意,您不需要()在 if 和 while 之后使用 Python 。