
How to Reverse a Linked List (Blind 75)
Problem Overview We are given the head of a singly linked list. We need to reverse the linked list. Follow-up: Solve it iteratively and recursively. Leetcode - Linked List Cycle Example Input: head = [1,2,3,4,5] Output: [5,4,3,2,1] Key Observations In a singly linked list, we can only traverse forward. Each node contains a pointer to the next node. Reversing the list means changing the direction of every next pointer. We must carefully store the next node before modifying links. Approach 1: Brute Force (Using Stack) Intuition Traverse the list. Push every node onto a stack. Pop nodes one by one to rebuild the list in reverse order. Code class Solution { public: ListNode* reverseList(ListNode* head) { if (!head) return NULL; stack<ListNode*> st; ListNode* curr = head; while (curr != NULL) { st.push(curr); curr = curr->next; } ListNode* newHead = st.top(); st.pop(); curr = newHead; while (!st.empty()) { curr->next = st.top(); st.pop(); curr = curr->next; } curr->next = NULL; return newHead; } }; Why It Is Not Optimal Uses extra data structure (stack). Requires additional memory. The problem can be solved in-place. Time and Space Complexity Time: O(n) Space: O(n) Approach 2: Three Pointer (Optimal Iterative) Intuition We maintain three pointers: ...








