# Reverse a Linked List

{% hint style="info" %}
<https://leetcode.com/problems/reverse-linked-list/>
{% endhint %}

{% tabs %}
{% tab title="Question" %}
Reverse a singly linked list.

**Example:**

```
Input: 1->2->3->4->5->NULL
Output: 5->4->3->2->1->NULL
```

{% endtab %}

{% tab title="Answer" %}
We swap the head with the previous node, which reverses the list.

```python
def reverseList(self, head: ListNode) -> ListNode:
        prev = None
        while head:
            # swaps nodes
            curr = head
            head = head.next
            curr.next = prev
            
            # stores the list
            prev = curr
        return prev
```

We can also do this in 3 lines in Python:

```python
def reverseList(self, head):
        """
        :type head: ListNode
        :rtype: ListNode
        """
        cur, prev = head, None
        while cur:
            cur.next, prev, cur = prev, cur, cur.next
        return prev
```

Using Tuple Unpacking. Or we can do it recursively:

```python
def reverseList(self, head: ListNode) -> ListNode:
        if not head or not head.next:
            return head
        node = self.reverseList(head.next)
        head.next.next = head
        head.next = None
        return node
```

{% endtab %}
{% endtabs %}


---

# 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://beesec.gitbook.io/algorithms/linked-lists/reverse-a-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.
