diff options
author | Aryadev Chavali <aryadev@aryadevchavali.com> | 2021-11-21 00:28:23 +0000 |
---|---|---|
committer | Aryadev Chavali <aryadev@aryadevchavali.com> | 2021-11-21 00:28:23 +0000 |
commit | 36d5eb111a4ffcebcdf9d95e56c09df056914f64 (patch) | |
tree | 54fb84bf1f3631f7fd08790dffb4e1e266be9fd9 | |
parent | 2f0fe5aef269cbac8a5dc78ef3dd3a005f6ff2db (diff) | |
download | algorithms-36d5eb111a4ffcebcdf9d95e56c09df056914f64.tar.gz algorithms-36d5eb111a4ffcebcdf9d95e56c09df056914f64.tar.bz2 algorithms-36d5eb111a4ffcebcdf9d95e56c09df056914f64.zip |
(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.
-rw-r--r-- | list.cpp | 15 |
1 files changed, 15 insertions, 0 deletions
@@ -42,6 +42,18 @@ List<T> *append(List<T> *lst, T value) return lst; } +/** Reverse a list + */ +template <typename T> +List<T> *reverse(List<T> *lst, List<T> *prev = NULL) +{ + auto next = lst->next; + lst->next = prev; + if (next == NULL) + return lst; + return reverse(next, lst); +} + template <typename T> std::ostream& operator<<(std::ostream& ostream, const List<T> *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; } |