擅长:python、mysql、java
<p>这应该起作用:</p>
<pre><code>class SingleLinkedList():
...
def add_after(self, n, element):
"""add element after the n-th node, counting from 1 (if n=0, add before the first node)"""
# check if we should add at the start...
if (n<=0):
self.add_first(element)
# ... or the end
elif (n>=self.size()):
self.add_last(element)
# otherwise, add after node n
else:
# start at the first node
node = self.get_head()
# loop over nodes until we reach node n
for i in range(n - 1):
node = node.get_next()
# make a new node from our element
new_node = Node(element,node.get_next())
# insert it after node n
node.set_next(new_node)
</code></pre>
<p>测试:</p>
<pre><code># test
q = SingleLinkedList()
q.add_first('A')
q.add_last('B')
q.add_last('C')
q.add_last('D')
q.add_last('E')
q.add_after(2, 'X')
print(q) # (A, B, X, C, D, E)
</code></pre>