Website Summary Files Commits Branches @commit @diff @stats
path: root / Additional / Additional-2024-IS / solutions / remove-nodes-stack.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-stack.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, 89 insertions, 0 deletions
-rw-r--r--Additional/Additional-2024-IS/solutions/remove-nodes-stack.cpp89
diff --git a/Additional/Additional-2024-IS/solutions/remove-nodes-stack.cpp b/Additional/Additional-2024-IS/solutions/remove-nodes-stack.cpp
new file mode 100644
index 0000000..a43dcfc
--- /dev/null
+++ b/Additional/Additional-2024-IS/solutions/remove-nodes-stack.cpp
@@ -0,0 +1,89 @@
+#include <climits>
+#include <iostream>
+#include <stack>
+
+struct ListNode
+{
+ int val;
+ ListNode* next;
+ ListNode()
+ : val(0)
+ , next(nullptr)
+ {}
+ ListNode(int x)
+ : val(x)
+ , next(nullptr)
+ {}
+ ListNode(int x, ListNode* next)
+ : val(x)
+ , next(next)
+ {}
+};
+
+class Solution
+{
+ public:
+ ListNode* removeNodes(ListNode* node)
+ {
+ if (!node || !node->next)
+ return node;
+
+ std::stack<ListNode*> listNodes;
+ int maxValue = INT_MIN;
+
+ ListNode* iter = nullptr;
+
+ while (node)
+ {
+ listNodes.push(node);
+ node = node->next;
+ }
+
+ while (!listNodes.empty())
+ {
+ ListNode* currentNode = listNodes.top();
+ listNodes.pop();
+
+ if (currentNode->val >= maxValue)
+ {
+ maxValue = currentNode->val;
+ currentNode->next = iter;
+ iter = currentNode;
+ }
+ else
+ {
+ delete currentNode;
+ }
+ }
+
+ return iter;
+ }
+};
+
+void freeList(ListNode* node)
+{
+ while (node)
+ {
+ ListNode* temp = node;
+ node = node->next;
+ delete temp;
+ }
+}
+
+int main()
+{
+ Solution s;
+
+ ListNode* result =
+ s.removeNodes(new ListNode(5, new ListNode(2, new ListNode(13, new ListNode(3, new ListNode(8))))));
+
+ ListNode* toDelete = result;
+
+ while (result)
+ {
+ std::cout << result->val << " ";
+ result = result->next;
+ }
+
+ freeList(toDelete);
+}