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