# 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) ### 執行結果  --- ## 用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; } }; ``` 
×
Sign in
Email
Password
Forgot password
or
By clicking below, you agree to our
terms of service
.
Sign in via Facebook
Sign in via Twitter
Sign in via GitHub
Sign in via Dropbox
Sign in with Wallet
Wallet (
)
Connect another wallet
New to HackMD?
Sign up