Website Summary Files Commits Branches @commit @diff @stats
path: root / Additional / Additional-2024-IS / solutions / remove-nodes-recursion.cpp
diff options
context:
space:
mode:
Commit98f6872efa0cd02e892ed5d7b836c6929d5c0e10 (patch)
Author
 Stoycho Kyosev <stoycho.kk@gmail.com>
2024-11-15 14:38:47 -0500
Committer
 Stoycho Kyosev <stoycho.kk@gmail.com>
2024-11-15 14:38:47 -0500
Files3f5a174c2081dda038ff8874f40a849b17a62c45 /Additional/Additional-2024-IS/solutions/remove-nodes-recursion.cpp
Data-structures-and-algorithms-98f6872efa0cd02e892ed5d7b836c6929d5c0e10.tar
Data-structures-and-algorithms-98f6872efa0cd02e892ed5d7b836c6929d5c0e10.tar.gz
Data-structures-and-algorithms-98f6872efa0cd02e892ed5d7b836c6929d5c0e10.zip
Parent54be018e9810ff7cfab307e17da1aa4288b9f414 (diff)
Add additional tasks
1 files changed, 75 insertions, 0 deletions
-rw-r--r--Additional/Additional-2024-IS/solutions/remove-nodes-recursion.cpp75
diff --git a/Additional/Additional-2024-IS/solutions/remove-nodes-recursion.cpp b/Additional/Additional-2024-IS/solutions/remove-nodes-recursion.cpp
new file mode 100644
index 0000000..bff2191
--- /dev/null
+++ b/Additional/Additional-2024-IS/solutions/remove-nodes-recursion.cpp
@@ -0,0 +1,75 @@
+#include <climits>
+#include <iostream>
+
+struct ListNode
+{
+ int val;
+ ListNode* next;
+ ListNode(int x, ListNode* next = nullptr)
+ : val(x)
+ , next(next)
+ {}
+};
+
+class Solution
+{
+ public:
+ ListNode* removeNodes(ListNode* head)
+ {
+ int maxVal = INT_MIN;
+ return removeNodesRecursive(head, maxVal);
+ }
+
+ private:
+ ListNode* removeNodesRecursive(ListNode* node, int& maxVal)
+ {
+ if (node == nullptr)
+ {
+ return nullptr;
+ }
+
+ ListNode* filteredNext = removeNodesRecursive(node->next, maxVal);
+
+ if (node->val >= maxVal)
+ {
+ maxVal = node->val;
+ node->next = filteredNext;
+ return node;
+ }
+ else
+ {
+ delete node;
+ return filteredNext;
+ }
+ }
+};
+
+void printList(ListNode* node)
+{
+ while (node)
+ {
+ std::cout << node->val << " ";
+ node = node->next;
+ }
+ std::cout << std::endl;
+}
+
+int main()
+{
+ Solution s;
+
+ ListNode* result =
+ s.removeNodes(new ListNode(5, new ListNode(2, new ListNode(13, new ListNode(3, new ListNode(8))))));
+
+ printList(result);
+
+ ListNode* current = result;
+ while (current)
+ {
+ ListNode* temp = current;
+ current = current->next;
+ delete temp;
+ }
+
+ return 0;
+}