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

时间:2014-10-21 23:11:09

标签: python generics linked-list

以下是问题:

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")

请帮我解决一下!

1 个答案:

答案 0 :(得分:0)

你可以使用递归来实现这个

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")