class Solution {
public:
ListNode* reverseList(ListNode* head)
{
ListNode *second_node, *rv;
/* If the list is zero nodes or one node, return it. */
if (head == nullptr) return head;
if (head->next == nullptr) return head;
/* Otherwise, using recursion, reverse all of the nodes but the first.
Keep a pointer to the original second node. */
second_node = head->next;
rv = reverseList(second_node);
/* Now, put the original first node at the end of the new list
and return the new list. */
second_node->next = head;
head->next = nullptr;
return rv;
}
};
|