gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 14:12:28 25 4
gpt4 key购买 nike

我已经在 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com