reverseLinkedList<T> function

LinkedListNode<T>? reverseLinkedList<T>(
  1. LinkedListNode<T>? head
)

Reverses a singly linked list iteratively

head - The head of the linked list to reverse Returns the new head of the reversed linked list

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

Implementation

LinkedListNode<T>? reverseLinkedList<T>(LinkedListNode<T>? head) {
  LinkedListNode<T>? prev;
  LinkedListNode<T>? current = head;
  LinkedListNode<T>? next;

  while (current != null) {
    // Store the next node
    next = current.next;

    // Reverse the link
    current.next = prev;

    // Move pointers forward
    prev = current;
    current = next;
  }

  return prev;
}