題目連接:https://leetcode.com/problems/reverse-linked-list/spa
方法一:迭代反轉.net
https://blog.csdn.net/qq_17550379/article/details/80647926講的很清楚code
/** * 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 = NULL; ListNode* cur = head; ListNode* lat; while(cur){ lat = cur -> next; cur -> next = pre; pre = cur; cur = lat; } return pre; } };
方法二:遞歸反轉blog
解決遞歸問題從最簡單的case入手。遞歸
(1)例如,對於鏈表1->2->3->4->5,leetcode
reverseList(head)返回的是5->4->3->2->1;get
reverseList(head->next)返回的是5->4->3->2;(由於head->next所指代的鏈表是2->3->4->5->NULL)it
以此類推。io
(2)對於reverseList(3)這個狀況,此時head爲3,head->next爲4,此時鏈表狀況以下:class
1->2->3->4<-5
head->next->next=head這一操做後,鏈表變爲:
而後,head->next=NULL,即
1->2->3<-4<-5
/** * 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 == NULL || head -> next == NULL) return head; ListNode *ans = reverseList(head -> next); head -> next -> next = head; head -> next = NULL; return ans; } };
此外,提供一個錯誤寫法:
/** * 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 == NULL || head -> next == NULL) return head; ListNode *ans = reverseList(head -> next); ans -> next = new ListNode(head -> val); return ans; } };
這種寫法的錯誤之處在於:
以reverseList(3)爲例,雖然ListNode *ans = reverseList(head -> next);返回的是5->4這個鏈表,不過ans指的是這個鏈表的第一個結點5,而後ans->next=new ListNode(head->val)後,其實在當前這一層遞歸中最終return的是5->3這個鏈表,並非返回想象中的5->4->3這個鏈表。
參考:https://blog.csdn.net/qq_17550379/article/details/80647926