From 884a3cc6d873053b72855107f9f5d95d7ad1706d Mon Sep 17 00:00:00 2001 From: Syndamia Date: Thu, 24 Nov 2022 20:07:46 +0200 Subject: [SDP/E1] Added work from today's exam --- .../Structures and data algorithms/Exam 1/ex2.cpp | 56 ++++++++++++++++++++++ 1 file changed, 56 insertions(+) create mode 100644 Year 2/Structures and data algorithms/Exam 1/ex2.cpp (limited to 'Year 2/Structures and data algorithms/Exam 1/ex2.cpp') 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 + +template +struct Node { + T value; + Node* next; + + Node(T value, Node* next = nullptr) : value(value), next(next) {} +}; + + +bool makeTotal(Node* head) { + int len = 0; + for (Node* i = head; i != nullptr; i = i->next) + len++; + if (len < 3) return false; + + Node* prev = head; + Node* 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* list = new Node(1, new Node(-4, new Node(-5, new Node(-1, new Node(4))))); + Node* list = new Node(10, new Node(-5, new Node(-5, new Node(-15, new Node(2))))); + + std::cout << makeTotal(list) << std::endl; + for (Node* i = list; i != nullptr; i = i->next) + std::cout << i->value << " "; + std::cout << std::endl; + + Node* tmp = nullptr; + while (list != nullptr) { + tmp = list->next; + delete list; + list = tmp; + } +} -- cgit v1.3.1-26-gb76a