aboutsummaryrefslogtreecommitdiff
path: root/list.cpp
diff options
context:
space:
mode:
authorAryadev Chavali <aryadev@aryadevchavali.com>2021-11-21 00:28:23 +0000
committerAryadev Chavali <aryadev@aryadevchavali.com>2021-11-21 00:28:23 +0000
commit36d5eb111a4ffcebcdf9d95e56c09df056914f64 (patch)
tree54fb84bf1f3631f7fd08790dffb4e1e266be9fd9 /list.cpp
parent2f0fe5aef269cbac8a5dc78ef3dd3a005f6ff2db (diff)
downloadalgorithms-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.
Diffstat (limited to 'list.cpp')
-rw-r--r--list.cpp15
1 files changed, 15 insertions, 0 deletions
diff --git a/list.cpp b/list.cpp
index 593a87e..5dc6d18 100644
--- a/list.cpp
+++ b/list.cpp
@@ -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;
}