deleteByValue<T> function
Deletes the first node with the specified value
head - The head of the linked list
value - The value to delete
Returns the new head of the linked list
Time Complexity: O(n) where n is the length of the list Space Complexity: O(1)
Implementation
LinkedListNode<T>? deleteByValue<T>(LinkedListNode<T>? head, T value) {
// Handle empty list
if (head == null) return null;
// Handle deletion of the first node
if (head.value == value) {
return head.next;
}
LinkedListNode<T>? current = head;
while (current!.next != null) {
if (current.next!.value == value) {
current.next = current.next!.next;
break;
}
current = current.next;
}
return head;
}