# Problem 206: Reverse Linked List

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

## 思路

这是一道经典并且基本的题目，理解这道题可以很好地理解 Linked List。先附上一个讲解的视频

> <https://www.youtube.com/watch?v=sYcOK51hl-A>

* 反转链表，主要地是要学会反转指针
* 思路是：1->2->3->4 现在要变成 1<-2<-3<-4，也就是说每个 pointer 都变为指向之前的 node，那么当前的 node 指向一个新设置的 prev node

![](/files/-Lpv9xVHVhgqjE3mmCSS)

![](/files/-Lpv9xVJDgJXSSxoLi8a)

![](/files/-Lpv9xVLMCHmrDN0tLc8)

![](/files/-Lpv9xVNPaXhZS4vP0A5)

## 复杂度

* 时间复杂度：\`O(n)\`
* 空间复杂度：\`O(1)\`

```java
/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
public class Solution {
    public ListNode reverseList(ListNode head) {
        if (head == null) {
            return head;
        }

        ListNode prev = null;
        while (head != null) {
            ListNode temp = head.next;
            head.next = prev;
            prev = head;
            head = temp;
        }
        return prev;
    }
}
```

## 易错点

1. 始终牢记一点就是，prev和next进行交换
2. 在反转指针的过程中，当断开链接的时候，我们就对剩下的元素失去了track，所以提前用temp存起来，以后用的时候再调出来。
3. head指针其实是current指针，随着他的移动，不停地更新链表
4. 最后结束的时候，其实头是prev指针
5. while循环一遍的时候并没有交换完成一遍，循环好几遍的时候才完成指针的反转


---

# 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://liuyang89116.gitbook.io/my-leetcode-book/chapter_4_linked_list/reverse-linked-list/problem_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.
