# Leetcode [No. 206] Reverse Linked List (EASY) ## 題目 https://leetcode.com/problems/reverse-linked-list/ ## 思路 + 這個就是透過while,走一圈,結束後return. ```c++= /** * 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) { return head; } ListNode* slow = nullptr; ListNode* fast = head->next; while(fast != nullptr) { head->next = slow; // update ptr; slow = head; head = fast; fast = fast->next; } head->next =slow; return head; } }; ``` ### 解法分析 + time complexity: O(n) ### 執行結果 ![image](https://hackmd.io/_uploads/ByOoXAAU6.jpg) --- ## 用recursive版本再寫一次 + 這個版本很重要,面試必考!!! ```c++= class Solution { public: ListNode* reverseList(ListNode* head) { if (head == nullptr || head->next == nullptr) return head; ListNode* last = reverseList(head->next); head->next->next = head; head->next = nullptr; return last; } }; ``` ![image](https://hackmd.io/_uploads/Hk7J8lCell.png)