Python 3 递归链表节点插入

标签 python python-3.x algorithm

我正在尝试创建一个递归函数以在特定位置插入链表以解决 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/

相关文章:

java - 问题插入heapsort

python - Enthought Canopy 编辑器。使用 TAB 完成阅读文档

python - 使 matplotlib 时间序列 'spaghetti' 图中的线条变粗

python - 基于无组织表创建字典的SQL语句

python - 在 python 3 中展平多维数组

algorithm - 启发式和 A* 算法

algorithm - 这个作业最快的算法是什么?

python - 在 Python 多处理中的池进程之间传递消息

python - 为什么 Python dis 模块无法反汇编这个 .pyc 文件?

python - 在 Linux 环境中从 Python 为 Windows 创建可执行文件的最简单方法