Python 3递归LinkedList节点插入

时间:2018-04-01 15:24:14

标签: python python-3.x algorithm

我试图创建一个递归函数来插入某个位置的链表以解决hackerrank challenge,这是在python中教育自己的一部分。然而,(根据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)

我已经发表评论,试图解释我理解为什么是我的逻辑,所以如果有什么不清楚,请告诉我。

2 个答案:

答案 0 :(得分:0)

发布了一个被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 

答案 1 :(得分:0)

这是我的实现。希望能帮助到你。如有疑问,请随时提问。

def InsertNth(head: Optional[Node], position: int, data: Optional[Node]) -> Optional[Node]:
    """Returns a new list where the second list is spliced into, or inserted at, given an index."""
    if (position > 0):
        if (head is not None):
            return Node(head.data, splice(head.next, position - 1, data))
        else:
            if (data is not None):
                if (data.next is not None):
                    return Node(data.data, splice(head, position, data.next))
                else:
                    return Node(data.data, head)
            else:
                return None
    else:
        # If position <= 0, splice data list at start of head list
        # This is the same process whether the position < 0 from the start or becomes < 0.
        if (data is not None):
            if (data.next is not None):
                return Node(data.data, splice(head, position - 1, data.next))
            else:
                return Node(data.data, head)
        else:
            if (head is not None):
                return head
            else:
                return None