Reverse Linked List

interview_workbook/leetcode/linked_list /app/src/interview_workbook/leetcode/linked_list/reverse_linked_list.py
View Source

Algorithm Notes

Summary: Reverse Linked List — notes not yet curated.
Time: Estimate via loops/recurrences; common classes: O(1), O(log n), O(n), O(n log n), O(n^2)
Space: Count auxiliary structures and recursion depth.
Tip: See the Big-O Guide for how to derive bounds and compare trade-offs.

Big-O Guide

Source

"""
Reverse Linked List

Problem: Reverse Linked List
LeetCode link: https://leetcode.com/problems/reverse-linked-list/
Description: Reverse a singly linked list and return the reversed list.
"""

from src.interview_workbook.leetcode._registry import register_problem
from src.interview_workbook.leetcode._types import Category, Difficulty


class Solution:
    def solve(self, *args):
        """
        Reverse a linked list.
        Args: head (ListNode)
        Returns: ListNode head
        """
        head = args[0]
        prev, curr = None, head
        while curr:
            nxt = curr.next
            curr.next = prev
            prev = curr
            curr = nxt
        return prev


def demo():
    """Run a simple demonstration for Reverse Linked List problem."""
    from src.interview_workbook.leetcode._nodes import ListNode

    def build_list(nums):
        dummy = ListNode(0)
        curr = dummy
        for n in nums:
            curr.next = ListNode(n)
            curr = curr.next
        return dummy.next

    def list_to_str(node):
        vals = []
        while node:
            vals.append(str(node.val))
            node = node.next
        return "->".join(vals)

    s = Solution()
    head = build_list([1, 2, 3, 4, 5])
    print(f"Original list: {list_to_str(head)}")
    result = s.solve(head)
    print(f"Reversed list: {list_to_str(result)}")
    return f"[1,2,3,4,5] -> {list_to_str(result)}"


register_problem(
    id=206,
    slug="reverse_linked_list",
    title="Reverse Linked List",
    category=Category.LINKED_LIST,
    difficulty=Difficulty.EASY,
    tags=["linked_list"],
    url="https://leetcode.com/problems/reverse-linked-list/",
    notes="",
)