# 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](https://3288217904-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LxJcc9A1TOyn5a5HJQ4%2F-LxYFnblOvpIh_jbi8FK%2F-LxYQUWSuKMbVQaATcK8%2F3.jpg?alt=media\&token=2d54a756-ea17-4bbf-b25b-c792ee4118b3)

### 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 %}
