我正在尝试创建一个递归函数以在特定位置插入链表以解决 hackerrank challenge 问题,作为 python self 教育的一部分。但是,(根据 hackerrank)这似乎是不正确的。有人可以帮助解释我可能哪里出错了吗?
"""
Insert Node at a specific position in a linked list
head input could be None as well for empty list
Node is defined as
class Node(object):
def __init__(self, data=None, next_node=None):
self.data = data
self.next = next_node
return back the head of the linked list in the below method.
"""
def InsertNth(head, data, position):
# if we've found our position, then insert Node with pointer to next/None
if head == None or position == 0 :
return Node(data, head)
# if we're at the next to last position, then update it's pointer to our new Node
elif position == 1 :
head.next = Node(data, head.next)
# otherwise, step position down, and perform recursion
else :
InsertNth(head.next, data, position-1)
我已经在评论中尝试解释我所理解的逻辑,所以如果有任何不清楚的地方,请告诉我。
最佳答案
发布了一个被 hackerrank 接受的解决方案:
def InsertNth(head, data, position):
# if we have found our position, then create a new Node
if head == None or position == 0 :
return Node(data, head)
else :
next_node = head
while position > 1 :
next_node = next_node.next
position -= 1
next_node.next = Node(data, next_node.next)
return head
关于Python 3 递归链表节点插入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49599575/