Reverse Linked List - Leetcode Solution


πŸ’‘ Step-by-Step Thought Process

  1. Understand the problem: Reverse a singly linked list and return the new head.
  2. Initialize a pointer cur to head and prev to None.
  3. While cur is not None:
    • Store cur.next in temp to preserve the next node.
    • Set cur.next to prev to reverse the link.
    • Move prev to cur and cur to temp to advance the pointers.
  4. Return prev as the new head of the reversed list.

Code Solution


                

                

                

                

Detailed Explanation

Understanding the Problem: Reverse Linked List

The β€œReverse Linked List” problem asks us to reverse a singly linked list, so that the head becomes the tail, and all the links point in the opposite direction. This is a foundational problem in data structures, especially for understanding pointer manipulation in linked lists.

Example:

  • Input: 1 β†’ 2 β†’ 3 β†’ 4 β†’ 5 β†’ NULL
  • Output: 5 β†’ 4 β†’ 3 β†’ 2 β†’ 1 β†’ NULL

Why This Problem Matters

Reversing a linked list is one of the most common operations you may need to perform in both academic and real-world applications. It teaches the fundamentals of:

  • In-place data structure manipulation
  • Understanding of pointers and memory references
  • Iterative and recursive control flow

Optimal Approach: Iterative Reversal

We can reverse a singly linked list using an iterative approach by keeping track of three pointers:

  • prev: initially set to None
  • cur: the current node being processed
  • temp: stores the next node so we don't lose reference during reversal

Steps:

  1. Set cur = head and prev = None.
  2. While cur is not None:
    • Store cur.next in a temporary variable temp.
    • Set cur.next = prev to reverse the direction of the link.
    • Move prev to cur.
    • Move cur to temp.
  3. When the loop ends, prev will point to the new head of the reversed list.
  4. Return prev.

Example Walkthrough

Input: 1 β†’ 2 β†’ 3
Steps:

  • cur = 1, temp = 2, reverse link β†’ 1 β†’ None, move prev = 1, cur = 2
  • cur = 2, temp = 3, reverse link β†’ 2 β†’ 1, move prev = 2, cur = 3
  • cur = 3, temp = None, reverse link β†’ 3 β†’ 2, move prev = 3, cur = None
  • Return prev = 3 β†’ 2 β†’ 1

Time and Space Complexity

Time Complexity: O(n), where n is the number of nodes. Each node is visited once.
Space Complexity: O(1), as the reversal is done in-place using constant extra space.

Edge Cases to Consider

  • Empty list β†’ return None
  • Single-node list β†’ return the node itself
  • Already reversed list β†’ still works correctly due to uniform logic

Conclusion

The β€œReverse Linked List” problem is a staple in learning linked lists and pointer manipulation. It teaches how to carefully update node references to reverse the list efficiently in-place, and builds foundational skills for more complex linked list operations.

Get Personalized Support at AlgoMap Bootcamp πŸ’‘