Website Summary Files Commits Branches @commit @diff @stats
path: root / Additional / oddEvenList.cpp
blob: 05a95ac86b526e797ddfa1c59d4aad76b08312ee (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
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);
}