RESERVE A LINKED LIST
Reverse a Linked List – Iterative Approach
Introduction
Reversing a linked list is one of the most fundamental problems in data structures. It involves changing the direction of the links between nodes so that the last node becomes the first and vice versa.
Problem Statement
Given the head of a singly linked list, reverse the list and return the new head.
Example
Input:
1 -> 2 -> 3 -> 4 -> 5
Output:
5 -> 4 -> 3 -> 2 -> 1Solution Code
class Node {
constructor(newData) {
this.data = newData;
this.next = null;
}
}
function reverseList(head) {
let curr = head;
let prev = null;
let next;
while (curr !== null) {
next = curr.next;
curr.next = prev;
prev = curr;
curr = next;
}
return prev;
}Approach Used: Iterative Method
Idea
We traverse the linked list and reverse the direction of each pointer one by one.
How It Works
We use three pointers:
curr= current nodeprev= previous nodenext= to store next node temporarily
Steps:
Store next node (
next = curr.next)Reverse current link (
curr.next = prev)Move pointers forward:
prev = currcurr = next
Repeat until the end of the list
Why This Approach Was Chosen
Efficient and easy to understand
Works in a single traversal
No extra memory required
Alternative Approach
Recursive method
Elegant
Uses extra stack space
Why iterative?
Because it is more space-efficient and commonly preferred
Time and Space Complexity
Time Complexity: O(n)
Space Complexity: O(1)
Observation
We must store
nextbefore changing linksOtherwise, we lose access to the remaining list
Edge Cases
Empty list return null
Single node remains the same
Multiple nodes = reversed correctly
Comments
Post a Comment