Website Summary Files Commits Branches @commit @diff @stats
path: root / Seminar04 / linked-list-utils.h
blob: bf093ba541e996bb86572923cec08222c91b061e (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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
#include<iostream>
#include<initializer_list>

template<class T>
struct LinkedListNode {
    T data;
    LinkedListNode<T>* next;

    LinkedListNode(const T& elem, LinkedListNode<T>* n = nullptr) : data{elem}, next {n} {} 
};

template<class T>
void printLinkedList(const LinkedListNode<T>* ll) {
    const LinkedListNode<T>* iterate = ll;

    while(iterate) {
        std::cout << iterate->data << " ";
        iterate = iterate->next;
    }

    std::cout << std::endl;
}

template<class T>
void printLinkedList(const LinkedListNode<T>* ll, void (*print)(T)) {
    const LinkedListNode<T>* iterate = ll;

    while(iterate) {
        print(iterate->data);
        iterate = iterate->next;
    }

    std::cout << std::endl;
}

template<class T>
void printLinkedList(const LinkedListNode<T>* ll, void (*print)(const T&)) {
    const LinkedListNode<T>* iterate = ll;

    while(iterate) {
        print(iterate->data);
        iterate = iterate->next;
    }

    std::cout << std::endl;
}

template<class T>
LinkedListNode<T>* fromList(const std::initializer_list<T>& l) {
    LinkedListNode<T>* toReturn = nullptr;
    LinkedListNode<T>* iter = nullptr;

    for(const auto& elem : l) {
        LinkedListNode<T>* toInsert = new LinkedListNode<T>(elem);
        if(iter == nullptr) {
            toReturn = toInsert;
            iter = toInsert;
        }
        else {
            iter->next = toInsert;
            iter = iter->next;
        }
    }
    return toReturn;
}

template<class T>
void freeList(LinkedListNode<T>* ll) {
    while(ll) {
        LinkedListNode<T>* toDelete = ll;
        ll = ll->next;
        delete toDelete;
    }
}