# 206 Reverse Linked List

Reverse a singly linked list.

**The Idea:** Reverse the next pointer of every node. Consider the following example:

```
input:
1 -> 2 -> 3 -> 4 -> 5 -> null

start: first set head->next to null, but remember to store next
null <- 1 ...

now enter the while loop: terminate when iter_next is null

null <- 1 <- 2 ...
null <- 1 <- 2 <- 3 ...
null <- 1 <- 2 <- 3 <- 4 ...
null <- 1 <- 2 <- 3 <- 4 <- 5
```

**Complexity:** O(n) time and O(1) space

```python
# Definition for singly-linked list.
# class ListNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution(object):
    def reverseList(self, head):
        """
        :type head: ListNode
        :rtype: ListNode
        """
        if not head:
            return head

        iter_next = head.next
        head.next = None
        while iter_next:
            tmp = iter_next.next
            iter_next.next = head
            head = iter_next
            iter_next = tmp
        return head
```


---

# 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://maksimdan.gitbook.io/interview-practice-problems/leetcode_sessions/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.
