insertAfterValue<T> function

LinkedListNode<T>? insertAfterValue<T>(
  1. LinkedListNode<T>? head,
  2. T afterValue,
  3. T newValue
)

Inserts a new node with the given value after a node with the specified value

head - The head of the linked list afterValue - The value after which to insert newValue - The value to insert Returns the head of the linked list (unchanged if afterValue not found)

Time Complexity: O(n) where n is the length of the list Space Complexity: O(1)

Implementation

LinkedListNode<T>? insertAfterValue<T>(
  LinkedListNode<T>? head,
  T afterValue,
  T newValue,
) {
  LinkedListNode<T>? current = head;

  while (current != null) {
    if (current.value == afterValue) {
      LinkedListNode<T> newNode = LinkedListNode<T>(newValue);
      newNode.next = current.next;
      current.next = newNode;
      break;
    }
    current = current.next;
  }

  return head;
}