We will solve this problem in a very similar way as we have done in the last lesson.
Cases to Consider
Again, we’ll consider two cases while writing our code:
Node to be deleted is at position 0
Node to be deleted is not at position 0
The overall logic will stay the same as in the previous lesson except that we’ll change the code a bit to cater to position rather than a key.
Implementation
Without any further ado, let’s jump to the implementation:
xxxxxxxxxx
def delete_node_at_pos(self, pos):
if self.head:
cur_node = self.head
if pos == 0:
self.head = cur_node.next
cur_node = None
return
prev = None
count = 0
while cur_node and count != pos:
prev = cur_node
cur_node = cur_node.next
count += 1
if cur_node is None:
return
prev.next = cur_node.next
cur_node = None