> For the complete documentation index, see [llms.txt](https://code.taozirui.com/lc/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://code.taozirui.com/lc/data-structure/linked-list-1/reverse-linked-list.md).

# 206. Reverse Linked List

Reverse a linked list

**Thoughts:**&#x20;

1. Using Stack (time limit exceed)
2. Recursively: Find the second from the last node (if it Linked List contains more than two nodes), then reverse current two nodes by first creating a **cycle**, then cut the forward links (set it to be NULL/nullptr)
3. Having three pointers&#x20;
   1. first record next node and then set current node next to pre
   2. repeat for the next step: move pre to head and then move head to next
4. 1. having three pointers with dummy node:&#x20;
   2. pre always inserts cur->next right next to itself

**Code 2**

```cpp
/**
 * 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 || !head->next) return head;
        ListNode* node = reverseList(head->next);
        head->next->next = head;
        head->next = nullptr;

        return node;
    }
};
```

**Code 3**

```cpp
/**
 * 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) {
        ListNode * pre = nullptr;
        while(head){
            ListNode *next = head->next;
            head->next = pre;
            pre = head;
            head = next;
        }
        return pre;
    }
};
```

**Code 4**

```cpp
class Solution {
public:
    ListNode* reverseList(ListNode* head) {
        ListNode* pre = new ListNode(0);
        pre -> next = head;
        ListNode* cur = head; 
        while (cur && cur -> next) {
            ListNode* temp = pre -> next;
            pre -> next = cur -> next;
            cur -> next = cur -> next -> next; 
            pre -> next -> next = temp;
        }
        return pre -> next;
    }
};
```

Special Thanks to [jianchaolifighter](https://leetcode.com/jianchaolifighter)'s [Solution](https://leetcode.com/problems/reverse-linked-list/discuss/58130) and and [redace85](https://discuss.leetcode.com/user/redace85)'s [Solution](https://discuss.leetcode.com/topic/13317/accepted-c-solutions-both-iteratively-and-recursively)
