summaryrefslogtreecommitdiff
path: root/Year_1/Programming_2/data_structures/queue.cc
blob: 83984591a45d87e174d38e6e7221c7f05b842f27 (plain)
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
#include<iostream>

using namespace std;

template<typename T>
struct node {
    T value;
    node<T>* next;
};

template<class T>
class queue {
public:
    queue() : _head{nullptr} {}

    ~queue() {
        auto iter = _head;
        while(iter) {
            delete iter;
            iter = iter->next;
        }
    }

    queue<T>* enqueue(T val) {

        if(!_head) {
            _head = new node<T>{val, nullptr};
            _tail = _head;
        } else {
            _tail->next = new node<T>{val, nullptr};
            _tail = _tail->next;
        }

        return this;
    }

    node<T>* dequeue() {
        if(!_head) return nullptr;
        auto iter = _head;
        delete _head;
        _head = iter->next;
        return iter;
    }

    void print() {
        auto iter = _head;
        while(iter) {
            cout << iter->value << ' ';
            iter = iter->next;
        }
        cout << endl;
    }
private:
    node<T>* _head;
    node<T>* _tail;
};

int main() {
    queue<int>* q = new queue<int>();

    q->dequeue();
    q->enqueue(4)->enqueue(2)->enqueue(8);
    q->print();
    auto e = q->dequeue();
    if(e)
        cout << e->value << endl;
    q->enqueue(1);
    q->print();

    delete q;
    return 0;
}