Skip to main content
 首页 » 编程设计

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

2025年05月04日9kenshinobiy

这是一个非常简单的程序,用于在链接列表的末尾添加一个节点。我不知道我在做什么错误。与 hackerRank 的异常输出有关,或者我的代码中有错误。 我正在尝试实现 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) 

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

请您参考如下方法:

如果你必须在链表的末尾添加那么它不需要测试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 

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