0
鑑於該類鏈接值插入一個鏈接,給定索引
class Link:
"""A linked list.
>>> s = Link(1, Link(2, Link(3, Link(4))))
>>> len(s)
4
>>> s[2]
3
>>> s
Link(1, Link(2, Link(3, Link(4))))
"""
empty =()
def __init__(self, first, rest=empty):
self.first = first
self.rest = rest
def __getitem__(self, i):
if i == 0:
return self.first
else:
return self.rest[i-1]
def __len__(self):
return 1 + len(self.rest)
def __repr__(self):
if self.rest:
rest_str = ', ' + repr(self.rest)
else:
rest_str = ''
return 'Link({0}{1})'.format(self.first, rest_str)
我怎麼會寫這樣的功能?
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 ***"
究竟是你想做些什麼? – mlwn 2014-10-21 23:34:45
我試圖實現一個函數插入,它需要一個鏈接,一個值和一個索引,並將該值插入給定索引處的鏈接。假設鏈表已經至少有一個元素,並且它不返回任何東西;插入應改變鏈接列表 – 2014-10-21 23:39:06
你做了什麼嘗試?你是否有特定的問題,或只是問如何做一個任務? – Parker 2014-10-21 23:50:12