Website Summary Files Commits Branches @commit @diff @stats
path: root / Additional / oddEvenList.cpp
diff options
context:
space:
mode:
Commit8c1753a1a200cbe0c23c2178a35e1b8b8c57bf64 (patch)
Author
 Stoycho Kyosev <stoycho.kk@gmail.com>
2022-11-22 23:57:23 +0200
Committer
 Stoycho Kyosev <stoycho.kk@gmail.com>
2022-11-22 23:57:23 +0200
Files5ccc337050428a14c1ff73f5443d32031bbb1f38 /Additional/oddEvenList.cpp
Data-structures-and-algorithms-8c1753a1a200cbe0c23c2178a35e1b8b8c57bf64.tar
Data-structures-and-algorithms-8c1753a1a200cbe0c23c2178a35e1b8b8c57bf64.tar.gz
Data-structures-and-algorithms-8c1753a1a200cbe0c23c2178a35e1b8b8c57bf64.zip
Parent74f5fe6f7c4222fc52479c6ef598f830f6049949 (diff)
Add additional
1 files changed, 55 insertions, 0 deletions
-rw-r--r--Additional/oddEvenList.cpp55
diff --git a/Additional/oddEvenList.cpp b/Additional/oddEvenList.cpp
new file mode 100644
index 0000000..05a95ac
--- /dev/null
+++ b/Additional/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