class Node:
def __init__(self, data):
self.data = data
self.next = None
class LinkedList:
def __init__(self):
self.head = None
def append(self, data):
new_node = Node(data)
if not self.head:
self.head = new_node
return
last = self.head
while last.next:
last = last.next
last.next = new_node
def delete_at_position(self, position):
if not self.head:
return # empty list, nothing to delete
if position == 1:
self.head = self.head.next # remove head
return
curr = self.head
count = 1
while curr and count < position - 1:
curr = curr.next
count += 1
if not curr or not curr.next:
return # position out of range
curr.next = curr.next.next # skip the node at position
def __str__(self):
result = []
curr = self.head
while curr:
result.append(str(curr.data))
curr = curr.next
return ' -> '.join(result) + ' -> null'
# Driver code
ll = LinkedList()
for i in [1, 2, 3, 4, 5]:
ll.append(i)
print("Before deletion:", ll)
ll.delete_at_position(3)
print("After deletion at position 3:", ll)if position == 1:
self.head = self.head.next # remove head
handle deletion of the first node by moving head pointer
while curr and count < position - 1:
curr = curr.next
count += 1
advance to node before the one to delete
if not curr or not curr.next:
return # position out of range
check if position is valid within list length
curr.next = curr.next.next # skip the node at position
unlink the node at position by skipping it
Before deletion: 1 -> 2 -> 3 -> 4 -> 5 -> null
After deletion at position 3: 1 -> 2 -> 4 -> 5 -> null