From 36d5eb111a4ffcebcdf9d95e56c09df056914f64 Mon Sep 17 00:00:00 2001 From: Aryadev Chavali Date: Sun, 21 Nov 2021 00:28:23 +0000 Subject: (list)+recursive reverse algorithm for singly linked lists Pretty simple, returns the last node as that's the new root node. Uses default parameters to make sure the first node has next set to null. --- list.cpp | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/list.cpp b/list.cpp index 593a87e..5dc6d18 100644 --- a/list.cpp +++ b/list.cpp @@ -42,6 +42,18 @@ List *append(List *lst, T value) return lst; } +/** Reverse a list + */ +template +List *reverse(List *lst, List *prev = NULL) +{ + auto next = lst->next; + lst->next = prev; + if (next == NULL) + return lst; + return reverse(next, lst); +} + template std::ostream& operator<<(std::ostream& ostream, const List *lst) { @@ -57,5 +69,8 @@ int main(void) for (int i = 2; i < 10; ++i) lst = append(lst, i); std::cout << lst << std::endl; + lst = reverse(lst); + std::cout << lst << std::endl; + delete lst; return 0; } -- cgit v1.2.3-13-gbd6f