python:在给定索引的链接中插入一个值



以下是问题:

def insert(link, value, index):
    """Insert a value into a Link at the given index.
    >>> link = Link(1, Link(2, Link(3)))
    >>> insert(link, 9001, 0)
    >>> link
    Link(9001, Link(1, Link(2, Link(3))))
    >>> insert(link, 100, 2)
    >>> link
    Link(9001, Link(1, Link(100, Link(2, Link(3)))))
    >>> insert(link, 4, 5)
    Index out of bounds
    """
    "*** YOUR CODE HERE ***"

我写下的效果不佳的是:

i = 0
link_new = link(link.first)
while link.rest != Link.empty and i < index:
    link_new = link.rest
    i += 1
    if i == index:
        link_new.first = value
        link_new.rest = link.first, link.rest
    else: 
        print ("Index out of bounds")

请帮我把它修好!

您可以对此使用递归

def insert(link, value, index):
    if index == 0:
         link.first = value
    elif link.rest != Link.empty:
          insert(link.rest, value, index-1)
    else       
        print ("Index out of bounds")

相关内容

  • 没有找到相关文章