# 206.Reverse-Linked-List

## 206. Reverse Linked List

## 题目地址

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

<https://www.jiuzhang.com/solutions/palindrome-partitioning-ii/>

## 题目描述

```
Reverse a linked list.
```

## 代码

### Approach 1: 使用while Iterative

1. 保存next 节点
2. curr的next节点指向prev节点
3. prev保存curr节点
4. curr保存next节点

```java
public class Solution {
    public ListNode reverseList(ListNode head) {
    ListNode prev = null;
    ListNode curr = head;

    // prev => cur => next
    while(curr != null) {
      ListNode next = curr.next;
      curr.next = prev;
      prev = curr;
      curr = next;
    }

    head = prev;

    return head;
  }
}
```

### Approach #2 Recursive

n1 → … → nk-1 → **nk** → nk+1 ← … ← nm

**Complexity analysis**

* Time complexity : &#x4F;*(\_n). Assume that n is the list's length, the time complexity is O*(*n*).
* Space complexity : &#x4F;*(\_n*). The extra space comes from implicit stack space due to recursion. The recursion could go up to n\_ levels deep.

```java
public ListNode reverseList(ListNode head) {
  if (head == null || head.next == null) return head;
  //  head => next <= next.next <=
  ListNode p = reverseList(head.next);
  head.next.next = head;
  head.next = null;
  return p;
}
```


---

# 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://wentao-shao.gitbook.io/leetcode/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.
