Leetcode 206. Reverse Linked List
包含迴圈和遞迴寫法
class Solution {
public:
ListNode* reverseList(ListNode* head) {
if (!head || !head->next) {
return head;
}
ListNode* fa = reverseList(head->next);
head->next->next = head;
head->next = nullptr;
return fa;
}
};
class Solution1 {
public:
ListNode* reverseList(ListNode* head) {
if(!head || !head->next)
return head;
ListNode* future = head->next, *copy = nullptr, *prev = nullptr;
do {
copy = future->next;
future->next = head;
head->next = prev;
prev = head;
head = future;
future = copy;
} while(copy);
return head;
}
};