Summary Files Commits Branches @commit @diff @stats
path: root / Year 2 / Structures and data algorithms / Exam 1 / ex2.cpp
diff options
context:
space:
mode:
1 files changed, 56 insertions, 0 deletions
-rw-r--r--Year 2/Structures and data algorithms/Exam 1/ex2.cpp56
diff --git a/Year 2/Structures and data algorithms/Exam 1/ex2.cpp b/Year 2/Structures and data algorithms/Exam 1/ex2.cpp
new file mode 100644
index 0000000..99128d0
--- /dev/null
+++ b/Year 2/Structures and data algorithms/Exam 1/ex2.cpp
@@ -0,0 +1,56 @@
+#include <iostream>
+
+template <typename T>
+struct Node {
+ T value;
+ Node<T>* next;
+
+ Node(T value, Node<T>* next = nullptr) : value(value), next(next) {}
+};
+
+
+bool makeTotal(Node<int>* head) {
+ int len = 0;
+ for (Node<int>* i = head; i != nullptr; i = i->next)
+ len++;
+ if (len < 3) return false;
+
+ Node<int>* prev = head;
+ Node<int>* next = head->next->next;
+ head = head->next;
+ bool balanced = true;
+ while (next != nullptr) {
+ if (prev->value + next->value != head->value) {
+ balanced = false;
+ break;
+ }
+
+ prev = prev->next;
+ head = head->next;
+ next = next->next;
+ }
+
+ if (!balanced) {
+ prev->next = next;
+ delete head;
+ makeTotal(prev);
+ }
+ return balanced;
+}
+
+int main() {
+ // Node<int>* list = new Node<int>(1, new Node<int>(-4, new Node<int>(-5, new Node<int>(-1, new Node<int>(4)))));
+ Node<int>* list = new Node<int>(10, new Node<int>(-5, new Node<int>(-5, new Node<int>(-15, new Node<int>(2)))));
+
+ std::cout << makeTotal(list) << std::endl;
+ for (Node<int>* i = list; i != nullptr; i = i->next)
+ std::cout << i->value << " ";
+ std::cout << std::endl;
+
+ Node<int>* tmp = nullptr;
+ while (list != nullptr) {
+ tmp = list->next;
+ delete list;
+ list = tmp;
+ }
+}