Website Summary Files Commits Branches @commit @diff @stats
path: root / Additional / Additional-2022-CS / oddEvenList.cpp
diff options
context:
space:
mode:
Commit9eed63a37a808c59990feaaaa3e1725dfdd31f3c (patch)
Author
 Stoycho Kyosev <stoycho.kk@gmail.com>
2023-10-30 22:33:14 +0200
Committer
 Stoycho Kyosev <stoycho.kk@gmail.com>
2023-10-30 22:33:14 +0200
Filesbc22e2b8407f9207c7a5a8ef999f41446c0cee19 /Additional/Additional-2022-CS/oddEvenList.cpp
Data-structures-and-algorithms-9eed63a37a808c59990feaaaa3e1725dfdd31f3c.tar
Data-structures-and-algorithms-9eed63a37a808c59990feaaaa3e1725dfdd31f3c.tar.gz
Data-structures-and-algorithms-9eed63a37a808c59990feaaaa3e1725dfdd31f3c.zip
Parent0f17a224d2934c748b32b908f74724b3299d263a (diff)
Add SI consultation
1 files changed, 55 insertions, 0 deletions
-rw-r--r--Additional/Additional-2022-CS/oddEvenList.cpp55
diff --git a/Additional/Additional-2022-CS/oddEvenList.cpp b/Additional/Additional-2022-CS/oddEvenList.cpp
new file mode 100644
index 0000000..05a95ac
--- /dev/null
+++ b/Additional/Additional-2022-CS/oddEvenList.cpp
@@ -0,0 +1,55 @@
+#include"../Seminar04/linked-list-utils.h"
+
+using ListNode = LinkedListNode<int>;
+
+ListNode* oddEvenList(ListNode* head) {
+ if(head == nullptr || head->next == nullptr)
+ return head;
+
+ ListNode* oddStart = nullptr;
+ ListNode* oddIter = nullptr;
+
+ ListNode* evenStart = nullptr;
+ ListNode* evenIter = nullptr;
+
+ bool odd = true;
+
+ while(head) {
+ ListNode*& curr = odd ? oddIter : evenIter;
+
+ if(curr == nullptr) {
+ curr = head;
+ if(odd)
+ oddStart = head;
+ else
+ evenStart = head;
+ }
+ else {
+ curr->next = head;
+ curr = curr->next;
+ }
+
+ head = head->next;
+ odd = !odd;
+ }
+
+ oddIter->next = evenStart;
+
+ if(evenIter != nullptr)
+ evenIter->next = nullptr;
+
+ return oddStart;
+}
+
+int main() {
+ ListNode* l = fromList({1, 2, 3, 4, 5});
+
+ ListNode* result = oddEvenList(l);
+ printLinkedList(result);
+ freeList(result);
+
+ ListNode* ls = fromList({2, 1, 3, 5, 6, 4, 7});
+ result = oddEvenList(ls);
+ printLinkedList(result);
+ freeList(result);
+} \ No newline at end of file