// Solution 2: Using recursive ListNode* reverseList(ListNode* head) { if (head == nullptr || head->next == nullptr) return head; std::function<ListNode*(ListNode*, ListNode*)> reverseHelper = [&](ListNode *curr, ListNode *prev) -> ListNode* { if (curr == nullptr) return prev; ListNode *next = curr->next; curr->next = prev; prev = curr; return reverseHelper(next, prev); }; return reverseHelper(head, nullptr); }
// Performs recursive step of reverse process Value *reverseHelper(Value *list, Value *newlist) { assert(isNull(list) || list->type == CONS_TYPE); if (isNull(list)) { return newlist; } else { newlist = cons(copy_Value(car(list)), newlist); return reverseHelper(cdr(list), newlist); } }
// Return a new list that is the reverse of the one that is passed in. Value *reverse(Value *list){ Value *newlist = makeNull(); newlist = reverseHelper(list, newlist); return newlist; }