Summary Files Commits Branches @commit @diff @stats
path: root / Year 2 / Structures and data algorithms / Exam 1 / ex2.cpp
diff options
context:
space:
mode:
Commit884a3cc6d873053b72855107f9f5d95d7ad1706d (patch)
Author
 Syndamia <kamen@syndamia.com>
2022-11-24 20:07:46 +0200
Committer
 Syndamia <kamen@syndamia.com>
2022-11-24 20:07:46 +0200
Files4dddd0d1fa72fcf514f649cbe8054e8ed3709bb4 /Year 2/Structures and data algorithms/Exam 1/ex2.cpp
uni-projects-884a3cc6d873053b72855107f9f5d95d7ad1706d.tar
uni-projects-884a3cc6d873053b72855107f9f5d95d7ad1706d.tar.gz
uni-projects-884a3cc6d873053b72855107f9f5d95d7ad1706d.zip
Parent81f851c6ea7988314812cf7cdb3cc94a6aa5cbf3 (diff)
[SDP/E1] Added work from today's exam
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;
+ }
+}