在链表中的指定索引处插入节点
我正在编写链接列表的代码,当我想在指定位置插入新节点时,我很困惑。我想知道为什么我们将位置减少1?这是代码:
def insert(self, data, index):
"""
Inserts a new Node containing data at index position
Insertion takes O(1) time but finding the node at the
insertion point takes O(n) time.
"""
if index == 0:
self.add(data)
if index > 0:
new = Node(data)
position = index
current = self.head
current.next_node
while position > 1:
current = new.next_node
position -= 1
prev_node = current
next_node = current.next_node
prev_node.next_node = new
new.next_node = next_node
I'm writing the code for Linked Lists and I'm confused when I want to insert a new node at the specified position. I'm wondering why we decrease the position by 1? Here is the code:
def insert(self, data, index):
"""
Inserts a new Node containing data at index position
Insertion takes O(1) time but finding the node at the
insertion point takes O(n) time.
"""
if index == 0:
self.add(data)
if index > 0:
new = Node(data)
position = index
current = self.head
current.next_node
while position > 1:
current = new.next_node
position -= 1
prev_node = current
next_node = current.next_node
prev_node.next_node = new
new.next_node = next_node
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

您这样做的原因是您尝试移动
当前
您如何做这没关系,无论您是将位置降低一个,做一个不同的循环还是做完全不同的事情 - 只要您做
current = New.ne.ne.next_node
索引
时间。这正是这样做
的。它运行该语句
index
次,因为position = index
要开始。替代方案是,它很可能应该是
current = current.next_node
,而不是current = new.ne.next_node
,因为new
永远不会更新。The reason you do it is that you try to move the
current
forwardindex
elements.How you do that does not matter, whether you decrease the position by one, do a different loop or do something entirely different - as long as you do
current = new.next_node
index
times.And that is exactly what
does. It runs that statement
index
times sinceposition = index
to begin with. An alternative would beNote that it most likely should be
current = current.next_node
, notcurrent = new.next_node
, sincenew
never gets updated.