# 206.Reverse Linked List

**206.Reverse Linked List**

难度:Easy

> 反转一个单链表。

```
示例:

输入: 1->2->3->4->5->NULL
输出: 5->4->3->2->1->NULL
```

进阶: 你可以迭代或递归地反转链表。你能否用两种方法解决这道题？

递归： 由于递归都是一层一层处理的，如果要递归，首先要处理最后一个节点，然后将剩余的继续反转，代码如下:

```
/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode* reverseList(ListNode* head) {
        if(!head) return NULL;
        if(!head->next) {head->next=NULL; return head;}
        ListNode* pt=head;
        while(pt->next->next)
        {
            pt=pt->next;
        }
        ListNode* t=pt->next;
        pt->next=NULL;
        t->next=reverseList(head);
        return t;
        
        
    }
};
```

迭代： 在遍历列表时，将当前节点的下一个节点之前前一个元素，实现反转：

```
/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode* reverseList(ListNode* head) {
        if(!head) return NULL;
        ListNode* prev=NULL;
        ListNode* curr=head;
        while(curr!=NULL)
        {
           ListNode* tmp=curr->next;
            curr->next=prev;
            prev=curr;
            curr=tmp;
        }

        

        return prev;
    }
    
};
```


---

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