Introduction
Reversing a Linked List means changing the direction of node connections.
The task is to:
- reverse every next pointer
- make tail node the new head
- traverse list in opposite direction
Example:
Input:
1 -> 2 -> 3 -> 4 -> 5
Output:5 -> 4 -> 3 -> 2 -> 1
Explanation:
Every pointer direction is reversed.Original head becomes tail.
Original tail becomes new head.
This problem is one of the most important applications of:
Pointer Manipulation Constraints
1 <= Number of Nodes <= 10^5
-10^9 <= Node Value <= 10^9 Approach 1 : Brute Force (Using Array)
Explanations:
Explanation:
The idea is:
- store linked list values in array
- reverse array
- rebuild linked list
Steps:
- Traverse linked list.
- Store node values.
- Reverse array.
- Create reversed linked list.
This approach works but:
- uses extra memory
So pointer reversal is preferred.
Dry Run
Input:1 -> 2 -> 3 -> 4
Step 1:
Store values
[1,2,3,4]
Step 2:
Reverse array
[4,3,2,1]
Output:
4 -> 3 -> 2 -> 1
Practice :
Complexity Analysis :
Time Complexity:- O(n)
Explanation :
Each node is visited once.
Space Complexity:- O(n)
Explanation :Extra array is used.
Approach 2 : Optimal Solution(Using Pointer Reversal)
Explanations:
Explanation:
This is the most optimized and interview-preferred solution.
The idea is:
- maintain three pointers:
prev
current
nextNode - reverse links one by one
This avoids extra memory usage.
Dry Run
Input:1 -> 2 -> 3 -> 4
Initial:
prev = NULL
current = 1
Step 1:
1 -> NULL
Step 2:
2 -> 1
Step 3:
3 -> 2
Step 4:
4 -> 3
Output:
4 -> 3 -> 2 -> 1
Practice :