# 206. Reverse Linked List

## Description

See: <https://leetcode.com/problems/reverse-linked-list/>

## Solution

Standard reverse a linked list question. Implemented both iteratively and recursively.

### Iterative

```python
class Solution:
    def reverseList(self, head: Optional[ListNode]) -> Optional[ListNode]:
        node = head
        prev = None
        while node != None:
            next_node = node.next
            node.next = prev
            prev = node
            node = next_node
        return prev
```

Time complexity: O(n)

Space complexity: O(1)

### Recursive

```python
class Solution:
    def reverseList(self, head: Optional[ListNode]) -> Optional[ListNode]:
        def helper(head, prev):
            if not head:
                return prev
            temp = head.next
            head.next = prev
            return helper(temp, head)
        return helper(head, None)
```

Time complexity: O(n)

Space complexity: O(n) - recursive stack is the size of the linked list


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://monica-granbois.gitbook.io/cs-theory-and-problems/problems/leetcode/206.-reverse-linked-list.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
