# 206. Reverse Linked List

{% hint style="success" %}

### Key idea: record pre-node + current node + change next direction

### 核心： 记录前一个节点 ＋ 记录当前节点 ＋ 改变指针方向&#x20;

{% endhint %}

![process of reverse a linked list](/files/-LxYQUWSuKMbVQaATcK8)

### Solution

`temp` records next node, `head` is current node, `preNode` is the pre-node of `head`. Don't forget to initialise `preNode = NULL`, return new head.

`temp` 记录下一个节点，`head`表示当前节点，`preNode`表示`head`的母节点。必须初始化`preNode=NULL`，并且最后返回新的头节点（即最后一个节点）。

1. record next node temporally
2. let head.next point to preNode
3. move to next node
4. 暂时记录下一个节点
5. 让head.next指向前一个节点
6. 指针后移一位

### Python syntax

{% tabs %}
{% tab title="Java" %}

```java
class Solution {
    public ListNode reverseList(ListNode head) {
        if(head == null || head.next == null) return head;
        ListNode pre = null;
        ListNode curr = new ListNode();
        curr = head;
        while(curr != null) {
            ListNode nextTemp = curr.next;
            curr.next = pre;
            pre = curr;
            curr = nextTemp;
        }
        return pre;
    }
}
```

{% endtab %}

{% tab title="Second Tab" %}

```python
# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution:
    def reverseList(self, head: ListNode) -> ListNode:
        pre = None
        
        while head != None:
            temp = head.next
            head.next = pre
            
            pre = head
            head = temp
            
        return pre
```

{% 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://r24zeng.gitbook.io/leetcode-notebook/wan-quan-an-zhao-jiu-zhang-suan-fa-shua-de-60-dao-zuo-you/vi.-linked-list/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.
