deleteAtPosition<T> function
Deletes the node at the specified position
head - The head of the linked list
position - The position of the node to delete (0-indexed)
Returns the new head of the linked list
Time Complexity: O(n) where n is the position Space Complexity: O(1)
Implementation
LinkedListNode<T>? deleteAtPosition<T>(LinkedListNode<T>? head, int position) {
// Handle empty list
if (head == null) return null;
// Handle deletion of the first node
if (position == 0) {
return head.next;
}
// Handle invalid position
if (position < 0) return head;
LinkedListNode<T>? current = head;
int currentPosition = 0;
// Traverse to the position before the node to delete
while (current != null && currentPosition < position - 1) {
current = current.next;
currentPosition++;
}
// If we reached the end or the next node doesn't exist, return original head
if (current == null || current.next == null) return head;
// Delete the node by updating the next pointer
current.next = current.next!.next;
return head;
}