<p>问题是<code>n</code>是你自己构造的<code>DLLNode</code>。默认情况下,<code>prev</code>和{<cd4>}被设置为<code>Null</code>;因此不能对它们调用任何方法。在</p>
<pre><code>def insert(self, item, index):
""" Inserts a node at the specified index. """
# Construct node.
current = self.head
n = DLLNode(item)
# Check index bounds.
if index > self.size:
return 'index out of range'
# If the list is empty...
if self.isEmpty():
self.head = n
self.head.setPrev(self.head)
else : #added else case to prevent overlap
for x in range(0,index-1): #Obtain the current
current = current.next #move to the next item
# If the index is the first node...
if index == 0:
n.setNext(self.head)
self.head = n
if self.size == 0:
self.prev = n
# If the index is the last node...
elif index == self.size:
current.setNext(n) #set n to be the next of current
n.setPrev(current) #set current to be the previous of n
# If the index is any other node...
else:
n.setNext(current.next)
n.setPrev(current)
if current.next != None :
current.next.setPrev(n)
current.setNext(n)
self.size += 1
</code></pre>
<p>最后一种情况如下:</p>
^{pr2}$
<p>与<code>C</code>下一个<code>current</code>X<code>the</code>下一个<code>of</code>当前<code>and</code>N<code>the</code>N<code>(new node). First we set the</code>上一个<code>and</code>下一个{<cd9>}N`:</p>
<pre><code> / \|
C < N >X
|\ /
</code></pre>
<p>现在我们检查<code>X</code>是否真的是一个真正的节点(尽管这是严格不必要的,因为上面处理了“最后一个节点”)。如果<code>X</code>不是<code>None</code>,我们将<code>X</code>的<code>prev</code>设置为<code>N</code>:</p>
<pre><code> / \|
C < N >X
|\-/
</code></pre>
<p>最后,我们不再需要<code>C</code>来指向<code>X</code>(否则我们无法调用<code>X</code>的函数),因此我们将<code>C</code>的<code>next</code>设置为<code>N</code>:</p>
<pre><code> / \|
C < N >X
|\-/
</code></pre>
<p>你能提供测试数据来测试实现是否正常工作吗?在</p>