--- tags: leetcode --- # [206. Reverse Linked List](https://leetcode.com/problems/reverse-linked-list/) --- # My Solution ## Solution 1: Iteration ### The Key Idea for Solving This Coding Question ### C++ Code ```cpp= /** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode() : val(0), next(nullptr) {} * ListNode(int x) : val(x), next(nullptr) {} * ListNode(int x, ListNode *next) : val(x), next(next) {} * }; */ class Solution { public: ListNode *reverseList(ListNode *head) { ListNode *newHead = nullptr; while (head != nullptr) { ListNode *x = head->next; head->next = newHead; newHead = head; head = x; } return newHead; } }; ``` ### Time Complexity ### Space Complexity ## Solution 2: Recursion ### The Key Idea for Solving This Coding Question ### C++ Code ```cpp= /** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode() : val(0), next(nullptr) {} * ListNode(int x) : val(x), next(nullptr) {} * ListNode(int x, ListNode *next) : val(x), next(next) {} * }; */ class Solution { public: ListNode *reverseList(ListNode *head) { if (head == nullptr) { return nullptr; } if (head->next == nullptr) { return head; } ListNode *p = reverseList(head->next); head->next->next = head; head->next = nullptr; return p; } }; ``` ### Time Complexity ### Space Complexity # Miscellaneous <!-- # Test Cases ``` [1,2,3,4,5] ``` ``` [1,2] ``` ``` [] ``` ``` [1,2,3,4,5,6] ``` ``` [1] ``` -->