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 -> 1

Solution 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 node

  • prev = previous node

  • next = to store next node temporarily

Steps:

  1. Store next node (next = curr.next)

  2. Reverse current link (curr.next = prev)

  3. Move pointers forward:

    • prev = curr

    • curr = next

  4. 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 next before changing links

  • Otherwise, we lose access to the remaining list

Edge Cases

  • Empty list  return null

  • Single node  remains the same

  • Multiple nodes = reversed correctly


Comments

Popular posts from this blog

THE DELIVERY MAN

EC2 LAUNCHING

SORT A LINKED LIST USING MERGE SORT