Reverse a singly linked list.
Input: 1->2->3->4->5->NULL
Output: 5->4->3->2->1->NULL
A linked list can be reversed either iteratively or recursively. Could you implement both?
/**
* 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 head;
auto *temp = head->next;
head->next = nullptr;
return reverseList(head, temp);
}
ListNode* reverseList(ListNode* current, ListNode* next) {
if (next == nullptr) return current;
auto *new_next = next->next;
next->next = current;
return reverseList(next, new_next);
}
};
/**
* 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 head;
auto *next = head->next;
auto *current = head;
head->next = nullptr;
while (next) {
auto *new_next = next->next;
next->next = current;
current = next;
next = new_next;
}
return current;
}
};