From 8c1753a1a200cbe0c23c2178a35e1b8b8c57bf64 Mon Sep 17 00:00:00 2001 From: Stoycho Kyosev Date: Tue, 22 Nov 2022 23:57:23 +0200 Subject: Add additional --- Additional/oddEvenList.cpp | 55 ++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 55 insertions(+) create mode 100644 Additional/oddEvenList.cpp (limited to 'Additional/oddEvenList.cpp') 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; + +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 -- cgit v1.3.1-23-gd82d